|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | +import logging |
| 4 | +import sys |
| 5 | +from pathlib import Path |
| 6 | +from traceback import FrameSummary, StackSummary |
| 7 | +from typing import Annotated, Any |
| 8 | + |
| 9 | +import typer |
| 10 | +from alive_progress import alive_bar |
| 11 | + |
| 12 | +from icij_worker import TaskState |
| 13 | +from icij_worker.cli.utils import AsyncTyper, eprint |
| 14 | +from icij_worker.http_ import TaskClient |
| 15 | +from icij_worker.objects import READY_STATES, Task, TaskError |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | +DEFAULT_SERVICE_ADDRESS = "http://localhost:8000" |
| 20 | + |
| 21 | +_ARGS_HELP = "task argument as a JSON string or file path" |
| 22 | +_GROUP_HELP = "task group" |
| 23 | +_SERVICE_URL_HELP = "service URL address" |
| 24 | +_POLLING_INTERVAL_S_HELP = "task state polling interval in seconds" |
| 25 | +_NAME_HELP = "registered task name" |
| 26 | +_RESULT_HELP = "get a task result" |
| 27 | +_START_HELP = "creates a new task and start it" |
| 28 | +_TASK_ID_HELP = "task ID" |
| 29 | +_WATCH_HELP = "watch a task until it's complete" |
| 30 | + |
| 31 | +TaskArgs = str |
| 32 | + |
| 33 | +task_app = AsyncTyper(name="tasks") |
| 34 | + |
| 35 | + |
| 36 | +@task_app.command(help=_START_HELP) |
| 37 | +async def start( |
| 38 | + name: Annotated[str, typer.Argument(help=_NAME_HELP)], |
| 39 | + args: Annotated[TaskArgs, typer.Argument(help=_ARGS_HELP)] = None, |
| 40 | + group: Annotated[ |
| 41 | + str | None, |
| 42 | + typer.Option("--group", "-g", help=_GROUP_HELP), |
| 43 | + ] = None, |
| 44 | + service_address: Annotated[ |
| 45 | + str, typer.Option("--ds-address", "-a", help=_SERVICE_URL_HELP) |
| 46 | + ] = DEFAULT_SERVICE_ADDRESS, |
| 47 | +): |
| 48 | + match args: |
| 49 | + case str(): |
| 50 | + as_path = Path(name) |
| 51 | + if as_path.exists(): |
| 52 | + args = json.loads(as_path.read_text()) |
| 53 | + else: |
| 54 | + args = json.loads(args) |
| 55 | + case None: |
| 56 | + args = dict() |
| 57 | + case _: |
| 58 | + raise TypeError(f"Invalid args {args}") |
| 59 | + client = TaskClient(service_address) |
| 60 | + async with client: |
| 61 | + task_id = await client.create_task(name, args, group=group) |
| 62 | + eprint(f"Task({task_id}) started !") |
| 63 | + eprint(f"Task({task_id}) 🛫") |
| 64 | + print(task_id) |
| 65 | + |
| 66 | + |
| 67 | +@task_app.command(help=_WATCH_HELP) |
| 68 | +async def watch( |
| 69 | + task_id: Annotated[str, typer.Argument(help=_TASK_ID_HELP)], |
| 70 | + service_address: Annotated[ |
| 71 | + str, typer.Option("--ds-address", "-a", help=_SERVICE_URL_HELP) |
| 72 | + ] = DEFAULT_SERVICE_ADDRESS, |
| 73 | + polling_interval_s: Annotated[ |
| 74 | + float, typer.Option("--polling-interval-s", "-p", help=_POLLING_INTERVAL_S_HELP) |
| 75 | + ] = 1.0, |
| 76 | +): |
| 77 | + client = TaskClient(service_address) |
| 78 | + async with client: |
| 79 | + task = await client.get_task(task_id) |
| 80 | + if task.state is READY_STATES: |
| 81 | + await _handle_ready(task, client, already_done=True) |
| 82 | + await _handle_alive(task, client, polling_interval_s) |
| 83 | + print(task_id) |
| 84 | + |
| 85 | + |
| 86 | +@task_app.command(help=_RESULT_HELP) |
| 87 | +async def result( |
| 88 | + task_id: Annotated[str, typer.Argument(help=_TASK_ID_HELP)], |
| 89 | + service_address: Annotated[ |
| 90 | + str, typer.Option("--ds-address", "-a", help=_SERVICE_URL_HELP) |
| 91 | + ] = DEFAULT_SERVICE_ADDRESS, |
| 92 | +) -> Any: |
| 93 | + client = TaskClient(service_address) |
| 94 | + async with client: |
| 95 | + res = await client.get_task_result(task_id) |
| 96 | + if isinstance(res, (dict, list)): |
| 97 | + res = json.dumps(res, indent=2) |
| 98 | + print(res) |
| 99 | + |
| 100 | + |
| 101 | +async def _handle_ready( |
| 102 | + task: Task, client: TaskClient, already_done: bool = False |
| 103 | +) -> None: |
| 104 | + match task.state: |
| 105 | + case TaskState.ERROR: |
| 106 | + await _handle_error(task, client) |
| 107 | + case TaskState.CANCELLED: |
| 108 | + await _handle_cancelled(task) |
| 109 | + case TaskState.DONE: |
| 110 | + if already_done: |
| 111 | + await _handle_already_done(task) |
| 112 | + else: |
| 113 | + await _handle_done(task) |
| 114 | + case _: |
| 115 | + raise ValueError(f"Unexpected task state {task.state}") |
| 116 | + |
| 117 | + |
| 118 | +async def _handle_error(task, client: TaskClient): |
| 119 | + error = await client.get_task_error(task.id) |
| 120 | + eprint( |
| 121 | + f"Task({task.id}) failed with the following" |
| 122 | + f" error:\n\n{_format_error(error)}" |
| 123 | + ) |
| 124 | + eprint(f"Task({task.id}) ❌") |
| 125 | + raise typer.Exit(code=1) |
| 126 | + |
| 127 | + |
| 128 | +async def _handle_cancelled(task): |
| 129 | + eprint(f"Task({task.id}) was cancelled !") |
| 130 | + eprint(f"Task({task.id}) 🛑") |
| 131 | + raise typer.Exit(code=1) |
| 132 | + |
| 133 | + |
| 134 | +async def _handle_already_done(task): |
| 135 | + eprint(f"Task({task.id}) ✅ is already completed !") |
| 136 | + |
| 137 | + |
| 138 | +async def _handle_done(task): |
| 139 | + eprint(f"Task({task.id}) 🛬") |
| 140 | + eprint(f"Task({task.id}) ✅") |
| 141 | + |
| 142 | + |
| 143 | +async def _handle_alive( |
| 144 | + task: Task, client: TaskClient, polling_interval_s: float |
| 145 | +) -> None: |
| 146 | + title = f"Task({task.id}) 🛫" |
| 147 | + stats = "(ETA: {eta})" |
| 148 | + monitor = "{percent}" |
| 149 | + progress_bar = alive_bar( |
| 150 | + title=title, manual=True, stats=stats, monitor=monitor, file=sys.stderr |
| 151 | + ) |
| 152 | + with progress_bar as bar: |
| 153 | + task_state = task.state |
| 154 | + while task_state not in READY_STATES: |
| 155 | + task = await client.get_task(task.id) |
| 156 | + task_state = task.state |
| 157 | + progress = task.progress or 0.0 |
| 158 | + bar(progress) # pylint: disable=not-callable |
| 159 | + await asyncio.sleep(polling_interval_s) |
| 160 | + if task_state in READY_STATES: |
| 161 | + await _handle_ready(task, client) |
| 162 | + |
| 163 | + |
| 164 | +def _format_error(error: TaskError) -> str: |
| 165 | + stack = StackSummary.from_list( |
| 166 | + [FrameSummary(f.name, f.lineno, f.name) for f in error.stacktrace] |
| 167 | + ) |
| 168 | + msg = f"{error.name}:\n{stack}\n{error.message}" |
| 169 | + if error.cause: |
| 170 | + msg += "\n cause by {error.cause}" |
| 171 | + return msg |
0 commit comments