macrostrat.task_runner 0.1.0__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.
- macrostrat/task_runner/__init__.py +22 -0
- macrostrat/task_runner/cancel.py +110 -0
- macrostrat/task_runner/context.py +18 -0
- macrostrat/task_runner/events.py +59 -0
- macrostrat/task_runner/execute.py +119 -0
- macrostrat/task_runner/output.py +70 -0
- macrostrat/task_runner/spec.py +46 -0
- macrostrat/task_runner/tail.py +49 -0
- macrostrat_task_runner-0.1.0.dist-info/METADATA +46 -0
- macrostrat_task_runner-0.1.0.dist-info/RECORD +11 -0
- macrostrat_task_runner-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Background tasks run with live terminal output and a cancel that acts like Ctrl-C."""
|
|
2
|
+
|
|
3
|
+
from .cancel import TaskCancelled, request_cancel
|
|
4
|
+
from .context import RunContext
|
|
5
|
+
from .events import SSE_HEADERS, output_events
|
|
6
|
+
from .execute import FINAL_STATES, Outcome, execute
|
|
7
|
+
from .output import read_all
|
|
8
|
+
from .spec import TaskSpec, load_registry
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"FINAL_STATES",
|
|
12
|
+
"Outcome",
|
|
13
|
+
"RunContext",
|
|
14
|
+
"SSE_HEADERS",
|
|
15
|
+
"TaskCancelled",
|
|
16
|
+
"TaskSpec",
|
|
17
|
+
"execute",
|
|
18
|
+
"load_registry",
|
|
19
|
+
"output_events",
|
|
20
|
+
"read_all",
|
|
21
|
+
"request_cancel",
|
|
22
|
+
]
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Cancelling a run the way Ctrl-C cancels a command.
|
|
2
|
+
|
|
3
|
+
In a terminal, Ctrl-C makes psycopg cancel the running statement and raises
|
|
4
|
+
`KeyboardInterrupt`, which unwinds through everything. Both halves are
|
|
5
|
+
reproduced here: `CancelWatcher` interrupts the task's main thread and cancels
|
|
6
|
+
its Postgres statements; `interruptible()` makes that interrupt raise
|
|
7
|
+
`TaskCancelled`, a `BaseException` no library `except Exception` swallows.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import _thread
|
|
11
|
+
import signal
|
|
12
|
+
import threading
|
|
13
|
+
from contextlib import contextmanager
|
|
14
|
+
from typing import Callable
|
|
15
|
+
|
|
16
|
+
from sqlalchemy import create_engine, text
|
|
17
|
+
|
|
18
|
+
from .output import control_channel
|
|
19
|
+
|
|
20
|
+
CANCEL = b"cancel"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class TaskCancelled(BaseException):
|
|
24
|
+
"""The run was cancelled from outside, between or during statements."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@contextmanager
|
|
28
|
+
def interruptible():
|
|
29
|
+
"""For the block, `_thread.interrupt_main()` raises `TaskCancelled` here.
|
|
30
|
+
|
|
31
|
+
Must be entered from the main thread, where signal handlers live; under
|
|
32
|
+
Celery that means the prefork or solo pool.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def handler(signum, frame):
|
|
36
|
+
raise TaskCancelled()
|
|
37
|
+
|
|
38
|
+
previous = signal.signal(signal.SIGINT, handler)
|
|
39
|
+
try:
|
|
40
|
+
yield
|
|
41
|
+
finally:
|
|
42
|
+
signal.signal(signal.SIGINT, previous)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class CancelWatcher(threading.Thread):
|
|
46
|
+
"""Waits for `cancel` on the run's control channel, then interrupts the run.
|
|
47
|
+
|
|
48
|
+
The interrupt is queued first, so it fires the moment the cancelled
|
|
49
|
+
statement returns; `on_cancel` then cancels the statements themselves.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(self, redis, run_id: str, *, on_cancel: Callable[[], None]):
|
|
53
|
+
super().__init__(name=f"cancel-watcher:{run_id}", daemon=True)
|
|
54
|
+
self.redis = redis
|
|
55
|
+
self.channel = control_channel(run_id)
|
|
56
|
+
self.on_cancel = on_cancel
|
|
57
|
+
self.cancelled = False
|
|
58
|
+
self._stopping = threading.Event()
|
|
59
|
+
|
|
60
|
+
def run(self):
|
|
61
|
+
pubsub = self.redis.pubsub(ignore_subscribe_messages=True)
|
|
62
|
+
pubsub.subscribe(self.channel)
|
|
63
|
+
try:
|
|
64
|
+
while not self._stopping.is_set():
|
|
65
|
+
message = pubsub.get_message(timeout=0.5)
|
|
66
|
+
if message is None or _bytes(message["data"]) != CANCEL:
|
|
67
|
+
continue
|
|
68
|
+
if self._stopping.is_set():
|
|
69
|
+
return
|
|
70
|
+
self.cancelled = True
|
|
71
|
+
_thread.interrupt_main()
|
|
72
|
+
self.on_cancel()
|
|
73
|
+
return
|
|
74
|
+
finally:
|
|
75
|
+
pubsub.close()
|
|
76
|
+
|
|
77
|
+
def stop(self):
|
|
78
|
+
self._stopping.set()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def request_cancel(redis, run_id: str) -> int:
|
|
82
|
+
"""Ask a running run to stop. Returns how many watchers heard it (0: none running)."""
|
|
83
|
+
return redis.publish(control_channel(run_id), CANCEL)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def cancel_backends(db_url: str, application_name: str) -> int:
|
|
87
|
+
"""Cancel whatever the run's connections are executing, from a connection of our own.
|
|
88
|
+
|
|
89
|
+
Every connection the run opens carries its `application_name`, so a second
|
|
90
|
+
one the library opens is covered too.
|
|
91
|
+
"""
|
|
92
|
+
engine = create_engine(db_url)
|
|
93
|
+
try:
|
|
94
|
+
with engine.connect() as conn:
|
|
95
|
+
rows = conn.execute(
|
|
96
|
+
text(
|
|
97
|
+
"SELECT pg_cancel_backend(pid) FROM pg_stat_activity"
|
|
98
|
+
" WHERE application_name = :name AND state = 'active'"
|
|
99
|
+
),
|
|
100
|
+
{"name": application_name},
|
|
101
|
+
).all()
|
|
102
|
+
return len(rows)
|
|
103
|
+
finally:
|
|
104
|
+
engine.dispose()
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _bytes(value) -> bytes:
|
|
108
|
+
if isinstance(value, str):
|
|
109
|
+
return value.encode()
|
|
110
|
+
return value
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import TextIO
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
@dataclass
|
|
6
|
+
class RunContext:
|
|
7
|
+
"""What a task may ask of its run.
|
|
8
|
+
|
|
9
|
+
Output written to `stdout` while the task runs reaches the stream already;
|
|
10
|
+
`write` is for a task that wants to address the stream explicitly.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
run_id: str
|
|
14
|
+
output: TextIO
|
|
15
|
+
|
|
16
|
+
def write(self, text: str) -> None:
|
|
17
|
+
self.output.write(text)
|
|
18
|
+
self.output.flush()
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""A run's output as Server-Sent Events, for an API route to return.
|
|
2
|
+
|
|
3
|
+
Each `data` is `{"d": chunk}`, JSON because a raw carriage return would end an
|
|
4
|
+
SSE line, with the Redis stream entry as its `id`, so a reconnecting
|
|
5
|
+
`EventSource` resumes where it left off. A comment keeps the connection alive
|
|
6
|
+
through quiet stretches, and `event: end` carries the final state.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from typing import AsyncIterator, Awaitable, Callable
|
|
11
|
+
|
|
12
|
+
from .execute import FINAL_STATES
|
|
13
|
+
from .output import output_key
|
|
14
|
+
from .tail import tail_output
|
|
15
|
+
|
|
16
|
+
SSE_HEADERS = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def output_events(
|
|
20
|
+
redis,
|
|
21
|
+
run_id: str,
|
|
22
|
+
*,
|
|
23
|
+
state: Callable[[], Awaitable[str | None]],
|
|
24
|
+
archived_log: Callable[[], Awaitable[str | None]],
|
|
25
|
+
since: str = "0-0",
|
|
26
|
+
disconnected: Callable[[], Awaitable[bool]] | None = None,
|
|
27
|
+
final_states: tuple[str, ...] = FINAL_STATES,
|
|
28
|
+
) -> AsyncIterator[str]:
|
|
29
|
+
"""Replay the stream from `since` and follow it until the run ends.
|
|
30
|
+
|
|
31
|
+
`redis` is an asyncio client. Once a finished run's stream has expired, the
|
|
32
|
+
application's archived copy is replayed instead.
|
|
33
|
+
"""
|
|
34
|
+
if await state() in final_states and not await redis.exists(output_key(run_id)):
|
|
35
|
+
log = await archived_log()
|
|
36
|
+
if log:
|
|
37
|
+
yield _event("0-0", log)
|
|
38
|
+
yield _end(await state())
|
|
39
|
+
return
|
|
40
|
+
|
|
41
|
+
async def finished() -> bool:
|
|
42
|
+
return (await state()) in final_states
|
|
43
|
+
|
|
44
|
+
async for item in tail_output(redis, run_id, since=since, finished=finished):
|
|
45
|
+
if disconnected is not None and await disconnected():
|
|
46
|
+
return
|
|
47
|
+
if item is None:
|
|
48
|
+
yield ": ping\n\n"
|
|
49
|
+
continue
|
|
50
|
+
yield _event(*item)
|
|
51
|
+
yield _end(await state())
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _event(entry_id: str, chunk: str) -> str:
|
|
55
|
+
return f"id: {entry_id}\ndata: {json.dumps({'d': chunk})}\n\n"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _end(state: str | None) -> str:
|
|
59
|
+
return f"event: end\ndata: {json.dumps({'state': state})}\n\n"
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Execute one run on the worker: output to its stream, cancellable like Ctrl-C.
|
|
2
|
+
|
|
3
|
+
The application keeps its own record of runs; this only executes one and
|
|
4
|
+
reports how it ended.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import traceback
|
|
9
|
+
from contextlib import contextmanager, redirect_stderr, redirect_stdout
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Any, Callable
|
|
12
|
+
from urllib.parse import urlencode, urlsplit, urlunsplit
|
|
13
|
+
|
|
14
|
+
from redis import Redis
|
|
15
|
+
|
|
16
|
+
from macrostrat.database import Database
|
|
17
|
+
|
|
18
|
+
from .cancel import CancelWatcher, TaskCancelled, cancel_backends, interruptible
|
|
19
|
+
from .context import RunContext
|
|
20
|
+
from .output import OutputStream, expire, read_all
|
|
21
|
+
|
|
22
|
+
# Rich reads these when it creates a console, so they must be set before the
|
|
23
|
+
# task imports anything that does. The worker's service should set them too.
|
|
24
|
+
TERMINAL_ENV = {
|
|
25
|
+
"FORCE_COLOR": "1",
|
|
26
|
+
"COLORTERM": "truecolor",
|
|
27
|
+
"TERM": "xterm-256color",
|
|
28
|
+
"COLUMNS": "120",
|
|
29
|
+
"LINES": "40",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
FINAL_STATES = ("succeeded", "failed", "cancelled", "killed")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Outcome:
|
|
37
|
+
state: str
|
|
38
|
+
result: Any = None
|
|
39
|
+
error: str | None = None
|
|
40
|
+
log: str = ""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def execute(
|
|
44
|
+
run_id: str,
|
|
45
|
+
task: Callable[[Database, RunContext], Any],
|
|
46
|
+
*,
|
|
47
|
+
db_url: str,
|
|
48
|
+
redis_url: str,
|
|
49
|
+
) -> Outcome:
|
|
50
|
+
"""Call `task(db, ctx)` with its output on the run's stream and return how it ended.
|
|
51
|
+
|
|
52
|
+
Must run in a main thread (see `interruptible`). `db` connects as
|
|
53
|
+
`task-run:<run_id>`, which a cancel looks for; so does any libpq connection
|
|
54
|
+
the task opens itself, through `PGAPPNAME`.
|
|
55
|
+
"""
|
|
56
|
+
for key, value in TERMINAL_ENV.items():
|
|
57
|
+
os.environ.setdefault(key, value)
|
|
58
|
+
|
|
59
|
+
redis = Redis.from_url(redis_url)
|
|
60
|
+
application_name = f"task-run:{run_id}"
|
|
61
|
+
task_db = Database(with_application_name(db_url, application_name))
|
|
62
|
+
output = OutputStream(redis, run_id)
|
|
63
|
+
ctx = RunContext(run_id=run_id, output=output)
|
|
64
|
+
watcher = CancelWatcher(
|
|
65
|
+
redis, run_id, on_cancel=lambda: cancel_backends(db_url, application_name)
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
outcome = Outcome(state="succeeded")
|
|
69
|
+
watcher.start()
|
|
70
|
+
try:
|
|
71
|
+
with (
|
|
72
|
+
_environment(PGAPPNAME=application_name),
|
|
73
|
+
redirect_stdout(output),
|
|
74
|
+
redirect_stderr(output),
|
|
75
|
+
interruptible(),
|
|
76
|
+
):
|
|
77
|
+
outcome.result = task(task_db, ctx)
|
|
78
|
+
except TaskCancelled:
|
|
79
|
+
outcome.state = "cancelled"
|
|
80
|
+
output.write("\n^C cancelled\n")
|
|
81
|
+
except BaseException as err:
|
|
82
|
+
outcome.state = "failed"
|
|
83
|
+
outcome.error = f"{type(err).__name__}: {err}"
|
|
84
|
+
output.write("\n" + traceback.format_exc())
|
|
85
|
+
finally:
|
|
86
|
+
watcher.stop()
|
|
87
|
+
output.flush()
|
|
88
|
+
task_db.session.rollback()
|
|
89
|
+
task_db.engine.dispose()
|
|
90
|
+
|
|
91
|
+
outcome.log = read_all(redis, run_id)
|
|
92
|
+
expire(redis, run_id)
|
|
93
|
+
redis.close()
|
|
94
|
+
return outcome
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def with_application_name(db_url: str, name: str) -> str:
|
|
98
|
+
"""The URL with `application_name` set, so the run's sessions can be found."""
|
|
99
|
+
parts = urlsplit(db_url)
|
|
100
|
+
query = (
|
|
101
|
+
parts.query
|
|
102
|
+
+ ("&" if parts.query else "")
|
|
103
|
+
+ urlencode({"application_name": name})
|
|
104
|
+
)
|
|
105
|
+
return urlunsplit(parts._replace(query=query))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@contextmanager
|
|
109
|
+
def _environment(**values: str):
|
|
110
|
+
previous = {key: os.environ.get(key) for key in values}
|
|
111
|
+
os.environ.update(values)
|
|
112
|
+
try:
|
|
113
|
+
yield
|
|
114
|
+
finally:
|
|
115
|
+
for key, value in previous.items():
|
|
116
|
+
if value is None:
|
|
117
|
+
os.environ.pop(key, None)
|
|
118
|
+
else:
|
|
119
|
+
os.environ[key] = value
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""The run's output stream: a Redis stream of raw terminal chunks."""
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
|
|
5
|
+
# Enough for hours of progress-bar redraws; the ledger keeps the archive.
|
|
6
|
+
MAXLEN = 100_000
|
|
7
|
+
# The stream outlives the run long enough to be replayed, then the row's copy serves.
|
|
8
|
+
STREAM_TTL_SECONDS = 7 * 24 * 3600
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def output_key(run_id: str) -> str:
|
|
12
|
+
return f"task-run:{run_id}:out"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def control_channel(run_id: str) -> str:
|
|
16
|
+
return f"task-run:{run_id}:ctl"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class OutputStream(io.TextIOBase):
|
|
20
|
+
"""A text sink that appends each flushed chunk to the run's stream.
|
|
21
|
+
|
|
22
|
+
Chunks keep their ANSI sequences, so a terminal in the browser renders what
|
|
23
|
+
a terminal on the worker would have. Rich flushes after every print and
|
|
24
|
+
every live-display frame; a plain `print` is flushed on its newline.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, redis, run_id: str, *, maxlen: int = MAXLEN):
|
|
28
|
+
self.redis = redis
|
|
29
|
+
self.key = output_key(run_id)
|
|
30
|
+
self.maxlen = maxlen
|
|
31
|
+
self._buffer: list[str] = []
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def encoding(self):
|
|
35
|
+
return "utf-8"
|
|
36
|
+
|
|
37
|
+
def writable(self):
|
|
38
|
+
return True
|
|
39
|
+
|
|
40
|
+
def isatty(self):
|
|
41
|
+
return True
|
|
42
|
+
|
|
43
|
+
def write(self, text: str) -> int:
|
|
44
|
+
self._buffer.append(text)
|
|
45
|
+
if "\n" in text:
|
|
46
|
+
self.flush()
|
|
47
|
+
return len(text)
|
|
48
|
+
|
|
49
|
+
def flush(self):
|
|
50
|
+
if not self._buffer:
|
|
51
|
+
return
|
|
52
|
+
data = "".join(self._buffer)
|
|
53
|
+
self._buffer.clear()
|
|
54
|
+
self.redis.xadd(self.key, {"d": data}, maxlen=self.maxlen, approximate=True)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def read_all(redis, run_id: str) -> str:
|
|
58
|
+
"""The whole stream as one string, for archiving."""
|
|
59
|
+
entries = redis.xrange(output_key(run_id), "-", "+")
|
|
60
|
+
return "".join(_text(fields[b"d"]) for _, fields in entries)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def expire(redis, run_id: str, ttl: int = STREAM_TTL_SECONDS) -> None:
|
|
64
|
+
redis.expire(output_key(run_id), ttl)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _text(value) -> str:
|
|
68
|
+
if isinstance(value, bytes):
|
|
69
|
+
return value.decode("utf-8", errors="replace")
|
|
70
|
+
return value
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from importlib import import_module
|
|
3
|
+
from importlib.metadata import entry_points
|
|
4
|
+
from typing import Callable
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel
|
|
7
|
+
|
|
8
|
+
# Macrostrat's packages register their tasks here; another application names its own group.
|
|
9
|
+
ENTRY_POINT_GROUP = "macrostrat.tasks"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class TaskSpec:
|
|
14
|
+
"""A task the runner may be asked to run.
|
|
15
|
+
|
|
16
|
+
`run` is the dotted path (`package.module:function`) of a callable
|
|
17
|
+
`(db, params, ctx) -> result`, imported only when the task executes, so a
|
|
18
|
+
process holding the catalog need not carry the task's dependencies.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
name: str
|
|
22
|
+
title: str
|
|
23
|
+
description: str
|
|
24
|
+
params: type[BaseModel]
|
|
25
|
+
run: str
|
|
26
|
+
|
|
27
|
+
def schema(self) -> dict:
|
|
28
|
+
return self.params.model_json_schema()
|
|
29
|
+
|
|
30
|
+
def parse(self, data: dict) -> BaseModel:
|
|
31
|
+
return self.params.model_validate(data)
|
|
32
|
+
|
|
33
|
+
def resolve(self) -> Callable:
|
|
34
|
+
module, _, attr = self.run.partition(":")
|
|
35
|
+
return getattr(import_module(module), attr)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def load_registry(group: str = ENTRY_POINT_GROUP) -> dict[str, TaskSpec]:
|
|
39
|
+
"""Every task registered in the entry-point `group`, by name."""
|
|
40
|
+
registry: dict[str, TaskSpec] = {}
|
|
41
|
+
for entry in entry_points(group=group):
|
|
42
|
+
for spec in entry.load():
|
|
43
|
+
if spec.name in registry:
|
|
44
|
+
raise ValueError(f"Task {spec.name!r} is registered twice")
|
|
45
|
+
registry[spec.name] = spec
|
|
46
|
+
return registry
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Replay a run's output stream, then follow it until the run is over."""
|
|
2
|
+
|
|
3
|
+
from typing import AsyncIterator, Awaitable, Callable
|
|
4
|
+
|
|
5
|
+
from .output import _text, output_key
|
|
6
|
+
|
|
7
|
+
Entry = tuple[str, str]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
async def tail_output(
|
|
11
|
+
redis,
|
|
12
|
+
run_id: str,
|
|
13
|
+
*,
|
|
14
|
+
since: str = "0-0",
|
|
15
|
+
finished: Callable[[], Awaitable[bool]],
|
|
16
|
+
poll_ms: int = 1_000,
|
|
17
|
+
keepalive_ms: int = 15_000,
|
|
18
|
+
count: int = 500,
|
|
19
|
+
) -> AsyncIterator[Entry | None]:
|
|
20
|
+
"""Yield `(entry_id, text)` from `since` onward; `None` every `keepalive_ms`
|
|
21
|
+
of silence, so the caller can keep its connection alive.
|
|
22
|
+
|
|
23
|
+
`finished` is consulted only after a quiet poll: a run that is still
|
|
24
|
+
producing output is plainly not over, and the ledger is the authority on
|
|
25
|
+
when it is. A last non-blocking read drains what was written between the
|
|
26
|
+
quiet poll and the state change.
|
|
27
|
+
"""
|
|
28
|
+
key = output_key(run_id)
|
|
29
|
+
last = since
|
|
30
|
+
quiet_ms = 0
|
|
31
|
+
while True:
|
|
32
|
+
batches = await redis.xread({key: last}, block=poll_ms, count=count)
|
|
33
|
+
if batches:
|
|
34
|
+
quiet_ms = 0
|
|
35
|
+
for _, entries in batches:
|
|
36
|
+
for entry_id, fields in entries:
|
|
37
|
+
last = _text(entry_id)
|
|
38
|
+
yield last, _text(fields[b"d"])
|
|
39
|
+
continue
|
|
40
|
+
if await finished():
|
|
41
|
+
batches = await redis.xread({key: last}, count=count)
|
|
42
|
+
for _, entries in batches or []:
|
|
43
|
+
for entry_id, fields in entries:
|
|
44
|
+
yield _text(entry_id), _text(fields[b"d"])
|
|
45
|
+
return
|
|
46
|
+
quiet_ms += poll_ms
|
|
47
|
+
if quiet_ms >= keepalive_ms:
|
|
48
|
+
quiet_ms = 0
|
|
49
|
+
yield None
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: macrostrat.task_runner
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Background tasks with live terminal output and a cancel that acts like Ctrl-C
|
|
5
|
+
Author: Daven Quinn
|
|
6
|
+
Author-email: Daven Quinn <code@davenquinn.com>
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
13
|
+
Requires-Dist: macrostrat-database>=4.7.0,<5.0.0
|
|
14
|
+
Requires-Dist: pydantic>=2,<3
|
|
15
|
+
Requires-Dist: redis>=4.5,<8
|
|
16
|
+
Requires-Python: >=3.10, <4
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# macrostrat.task_runner
|
|
20
|
+
|
|
21
|
+
Long-running tasks run on a Celery worker with their terminal output streamed
|
|
22
|
+
live to a browser, and a cancel that behaves like Ctrl-C. Used by Macrostrat's
|
|
23
|
+
management tasks and Mapboard's topology rebuilds.
|
|
24
|
+
|
|
25
|
+
The application keeps its own record of runs (a table with an id and a state)
|
|
26
|
+
and its own routes; this package supplies the parts in between:
|
|
27
|
+
|
|
28
|
+
- **Worker:** `execute(run_id, task, db_url=, redis_url=)` calls `task(db, ctx)`
|
|
29
|
+
with stdout and stderr sent, ANSI intact, to the Redis stream
|
|
30
|
+
`task-run:<id>:out`, and returns an `Outcome` (state, result, error, the whole
|
|
31
|
+
log). It must run in a main thread, as under Celery's prefork pool with one
|
|
32
|
+
task per child.
|
|
33
|
+
- **Cancel:** `request_cancel(redis, run_id)` publishes on the run's control
|
|
34
|
+
channel. The worker interrupts the task's main thread with `TaskCancelled`, a
|
|
35
|
+
`BaseException` no library `except Exception` swallows, and cancels the
|
|
36
|
+
statements of every Postgres session named `task-run:<id>`.
|
|
37
|
+
- **API:** `output_events(redis, run_id, state=, archived_log=)` yields
|
|
38
|
+
Server-Sent Events: the stream replayed from the start (or `Last-Event-ID`),
|
|
39
|
+
then followed until the run ends, or the archived log once the stream has
|
|
40
|
+
expired. Return it with `SSE_HEADERS` as `text/event-stream`.
|
|
41
|
+
- **Catalog:** `TaskSpec` and `load_registry(group)`, for applications that
|
|
42
|
+
register tasks through entry points.
|
|
43
|
+
|
|
44
|
+
A browser draws the stream with xterm.js at 120 columns, matching the
|
|
45
|
+
`COLUMNS` the worker sets. A process that will not stop is killed through
|
|
46
|
+
Celery (`revoke(terminate=True)`), and the application records that itself.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
macrostrat/task_runner/__init__.py,sha256=RkXTkdHXjfE5gguLCV4hcQ8j3gBbX0drM3l5knm74-k,561
|
|
2
|
+
macrostrat/task_runner/cancel.py,sha256=qQf9k5VJTTk6sqvGh6xV0IZ8P3hrbR62_DZ5jHBs10Q,3490
|
|
3
|
+
macrostrat/task_runner/context.py,sha256=MDEMjgk5SqchvHzViBrM8YJv4CrnX1xIIbDKHw_Cmpg,426
|
|
4
|
+
macrostrat/task_runner/events.py,sha256=UR-uBgkchWRBsX3pakwapJ7W4QVWRIJjpglP-kn0NcY,1966
|
|
5
|
+
macrostrat/task_runner/execute.py,sha256=mW2GPdRqEy0CKGM1skfqK_xTz-SwNgXyjFpVrY-fsE8,3511
|
|
6
|
+
macrostrat/task_runner/output.py,sha256=FTjKxHVSj9uP5eTx6si9A-g6-rCFhJ0zr-6KciOQtZ8,1984
|
|
7
|
+
macrostrat/task_runner/spec.py,sha256=PUdNt-tvd0Hi32lcK288b8morr6bJSQbsdtVu56OydY,1462
|
|
8
|
+
macrostrat/task_runner/tail.py,sha256=D-IavNUbFRpcjpzQPhQ-3q7vmZNPNzteYmXRdodvMJo,1640
|
|
9
|
+
macrostrat_task_runner-0.1.0.dist-info/WHEEL,sha256=G_-rrEibZr7OEM7zdH1dSO6s-VdjfnS5PA4CLAdI9Vw,80
|
|
10
|
+
macrostrat_task_runner-0.1.0.dist-info/METADATA,sha256=fkGklBp2D-kniRK5XhEoa7CSfakodM_e7HalfM1WO88,2321
|
|
11
|
+
macrostrat_task_runner-0.1.0.dist-info/RECORD,,
|