taskqx 0.7.0.dev0__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.
Files changed (52) hide show
  1. taskqx/__init__.py +118 -0
  2. taskqx/__main__.py +5 -0
  3. taskqx/admin.py +29 -0
  4. taskqx/broker/__init__.py +12 -0
  5. taskqx/broker/_time.py +25 -0
  6. taskqx/broker/redis.py +1665 -0
  7. taskqx/broker/redis_admin.py +395 -0
  8. taskqx/broker/redis_calls.py +387 -0
  9. taskqx/broker/redis_components.py +111 -0
  10. taskqx/broker/redis_maintenance.py +117 -0
  11. taskqx/broker/redis_observability.py +120 -0
  12. taskqx/broker/redis_scripts.py +177 -0
  13. taskqx/broker/redis_state_machine.py +214 -0
  14. taskqx/broker/sqlite.py +1385 -0
  15. taskqx/broker/sqlite_admin.py +469 -0
  16. taskqx/broker/sqlite_components.py +124 -0
  17. taskqx/broker/sqlite_maintenance.py +218 -0
  18. taskqx/broker/sqlite_migrations.py +57 -0
  19. taskqx/broker/sqlite_state_machine.py +363 -0
  20. taskqx/capabilities.py +46 -0
  21. taskqx/cli.py +227 -0
  22. taskqx/config.py +57 -0
  23. taskqx/consistency.py +50 -0
  24. taskqx/errors.py +37 -0
  25. taskqx/health.py +27 -0
  26. taskqx/interactive.py +40 -0
  27. taskqx/middleware.py +39 -0
  28. taskqx/naming.py +35 -0
  29. taskqx/observability.py +158 -0
  30. taskqx/pagination.py +43 -0
  31. taskqx/payloads.py +208 -0
  32. taskqx/protocols.py +180 -0
  33. taskqx/py.typed +1 -0
  34. taskqx/retry.py +139 -0
  35. taskqx/scheduler.py +134 -0
  36. taskqx/serialization.py +78 -0
  37. taskqx/shell.py +303 -0
  38. taskqx/submission/__init__.py +19 -0
  39. taskqx/submission/base.py +62 -0
  40. taskqx/submission/observability.py +71 -0
  41. taskqx/submission/redis.py +180 -0
  42. taskqx/submission/routing.py +93 -0
  43. taskqx/submission/service.py +110 -0
  44. taskqx/submission/sqlite.py +161 -0
  45. taskqx/tui.py +1048 -0
  46. taskqx/types.py +280 -0
  47. taskqx/worker.py +300 -0
  48. taskqx-0.7.0.dev0.dist-info/METADATA +275 -0
  49. taskqx-0.7.0.dev0.dist-info/RECORD +52 -0
  50. taskqx-0.7.0.dev0.dist-info/WHEEL +4 -0
  51. taskqx-0.7.0.dev0.dist-info/entry_points.txt +2 -0
  52. taskqx-0.7.0.dev0.dist-info/licenses/LICENSE +21 -0
taskqx/tui.py ADDED
@@ -0,0 +1,1048 @@
1
+ """Optional Textual operations console; imports Textual only when launched."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from datetime import datetime
7
+ from importlib.metadata import PackageNotFoundError, version
8
+ from typing import Any, ClassVar
9
+
10
+ try:
11
+ _TASKQX_VERSION = version("taskqx")
12
+ except PackageNotFoundError:
13
+ _TASKQX_VERSION = "unknown"
14
+
15
+
16
+ def _connection_label(backend: str, namespace: str | None) -> str:
17
+ return f"{backend}:{namespace}" if namespace else backend
18
+
19
+
20
+ def _truncate(value: object, limit: int) -> str:
21
+ text = str(value)
22
+ return text if len(text) <= limit else f"{text[: limit - 3]}..."
23
+
24
+
25
+ def _render_health_diagnostics(report: Any) -> str:
26
+ status_labels = {"ok": "OK", "warning": "WARNING", "error": "ERROR"}
27
+ lines = ["[bold]诊断信息[/]"]
28
+ for check in report.checks:
29
+ label = status_labels[check.status]
30
+ detail = f" · {check.detail}" if check.detail else ""
31
+ lines.append(f"[bold]{label} {check.name}[/]{detail}")
32
+ return "\n".join(lines)
33
+
34
+
35
+ def build_tui_app(
36
+ broker: Any,
37
+ *,
38
+ backend: str,
39
+ namespace: str | None,
40
+ namespace_factory: Any | None = None,
41
+ ) -> Any:
42
+ """Build a bounded, read-mostly Textual operations console."""
43
+ loaded_namespace = getattr(broker, "_namespace", namespace)
44
+ if not isinstance(loaded_namespace, str):
45
+ loaded_namespace = namespace
46
+
47
+
48
+ from rich.text import Text
49
+ from textual.app import App, ComposeResult # type: ignore[import-not-found]
50
+ from textual.binding import Binding, BindingType # type: ignore[import-not-found]
51
+ from textual.containers import ( # type: ignore[import-not-found]
52
+ Horizontal,
53
+ Vertical,
54
+ VerticalScroll,
55
+ )
56
+ from textual.screen import ModalScreen # type: ignore[import-not-found]
57
+ from textual.widgets import ( # type: ignore[import-not-found]
58
+ DataTable,
59
+ Footer,
60
+ Input,
61
+ ListItem,
62
+ ListView,
63
+ Static,
64
+ )
65
+
66
+ class TextInputModal(ModalScreen[str | None]):
67
+ """Centered modal prompt for search and command input."""
68
+
69
+ BINDINGS: ClassVar[list[BindingType]] = [
70
+ Binding("escape", "cancel", "取消", show=False),
71
+ ]
72
+ CSS = """
73
+ TextInputModal { align: center middle; background: transparent; }
74
+ #input-dialog { width: 72; max-width: 90%; height: auto; border: round $primary; background: $surface; padding: 1 2; }
75
+ #input-dialog-title { margin-bottom: 1; text-style: bold; color: $primary; }
76
+ #dialog-input { width: 1fr; }
77
+ """
78
+
79
+ def __init__(self, title: str, placeholder: str) -> None:
80
+ super().__init__()
81
+ self._title = title
82
+ self._placeholder = placeholder
83
+
84
+ def compose(self) -> ComposeResult:
85
+ with Vertical(id="input-dialog"):
86
+ yield Static(self._title, id="input-dialog-title")
87
+ yield Input(placeholder=self._placeholder, id="dialog-input")
88
+
89
+ def on_mount(self) -> None:
90
+ self.query_one("#dialog-input", Input).focus()
91
+
92
+ def on_input_submitted(self, event: Input.Submitted) -> None:
93
+ self.dismiss(event.value)
94
+
95
+ def action_cancel(self) -> None:
96
+ self.dismiss(None)
97
+
98
+ class HelpModal(ModalScreen[None]):
99
+ """Centered keyboard reference."""
100
+
101
+ BINDINGS: ClassVar[list[BindingType]] = [
102
+ Binding("escape", "dismiss_help", "关闭", show=False),
103
+ Binding("?", "dismiss_help", "关闭", show=False),
104
+ ]
105
+ CSS = """
106
+ HelpModal { align: center middle; background: transparent; }
107
+ #help-dialog { width: 76; max-width: 90%; height: auto; border: round $primary; background: $surface; padding: 1 2; }
108
+ #help-content { color: $text; }
109
+ """
110
+
111
+ def compose(self) -> ComposeResult:
112
+ with Vertical(id="help-dialog"):
113
+ yield Static(
114
+ "[bold]帮助[/]\n\n"
115
+ "0 Main · 1 Status · 2 Namespace · 3 Queue\n"
116
+ "↑↓ 预览 / Enter 选择 namespace 或 queue · r 刷新 · / 搜索 · : 命令\n"
117
+ "m/d/e 切换消息、DLQ、EQ · [ ] 翻页 · v 显示 payload\n"
118
+ "x 重放 · Delete 删除 · c 一致性修复 · q 退出\n\n"
119
+ "写操作会打开确认弹框;payload 仅显示在当前界面。\n"
120
+ "按 Esc 或 ? 关闭。",
121
+ id="help-content",
122
+ )
123
+
124
+ def action_dismiss_help(self) -> None:
125
+ self.dismiss(None)
126
+
127
+ class ConfirmModal(ModalScreen[bool]):
128
+ """Small explicit confirmation prompt for mutating operations."""
129
+
130
+ BINDINGS: ClassVar[list[BindingType]] = [
131
+ Binding("y", "confirm", "确认", show=False),
132
+ Binding("n", "cancel", "取消", show=False),
133
+ Binding("escape", "cancel", "取消", show=False),
134
+ ]
135
+ CSS = """
136
+ ConfirmModal { align: center middle; }
137
+ #confirm-dialog { width: 68; max-width: 90%; height: auto; border: round $warning; background: $surface; padding: 1 2; }
138
+ #confirm-title { margin-bottom: 1; text-style: bold; color: $warning; }
139
+ #confirm-hint { margin-top: 1; color: $text-muted; }
140
+ """
141
+
142
+ def __init__(self, title: str, description: str) -> None:
143
+ super().__init__()
144
+ self._title = title
145
+ self._description = description
146
+
147
+ def compose(self) -> ComposeResult:
148
+ with Vertical(id="confirm-dialog"):
149
+ yield Static(self._title, id="confirm-title")
150
+ yield Static(self._description, id="confirm-description")
151
+ yield Static("按 y 确认 · 按 n 或 Esc 取消", id="confirm-hint")
152
+
153
+ def action_confirm(self) -> None:
154
+ self.dismiss(True)
155
+
156
+ def action_cancel(self) -> None:
157
+ self.dismiss(False)
158
+
159
+ class OperationsApp(App[None]):
160
+ """Keyboard-first, bounded operations console."""
161
+
162
+ TITLE: str = "Taskqx Operations"
163
+ PAGE_SIZE = 25
164
+ BINDINGS: ClassVar[list[BindingType]] = [
165
+ Binding("0", "main", "主内容", show=False),
166
+ Binding("2", "namespaces", "命名空间", show=False),
167
+ Binding("1", "status", "状态", show=False),
168
+ Binding("3", "queues", "队列", show=False),
169
+ Binding("ctrl+c", "quit", show=False),
170
+ ("r", "refresh", "刷新"),
171
+ ("m", "messages", "消息"),
172
+ ("d", "dead_letters", "DLQ"),
173
+ ("e", "expired", "EQ"),
174
+ ("]", "next_page", "下一页"),
175
+ ("[", "previous_page", "上一页"),
176
+ ("/", "search", "搜索"),
177
+ ("v", "show_payload", "显示 payload"),
178
+ ("x", "replay", "重放"),
179
+ ("delete", "delete_record", "删除"),
180
+ ("c", "consistency_repair", "修复"),
181
+ (":", "command", "命令"),
182
+ ("?", "help", "帮助"),
183
+ ("q", "quit", "退出"),
184
+ ]
185
+
186
+ CSS = """
187
+ Screen { background: $background; color: $text; }
188
+ #dashboard { height: 1fr; }
189
+ #header { height: 1; padding: 0 1; background: $panel; color: $primary; }
190
+ #statusbar { width: 1fr; }
191
+ #activity { width: auto; color: $warning; margin-right: 1; }
192
+ #activity.hidden { display: none; }
193
+ #version { width: auto; text-align: right; }
194
+ #layout { height: 1fr; padding: 0 1; }
195
+ #sidebar { width: 32; min-width: 24; height: 1fr; margin-right: 1; }
196
+ #content { height: 1fr; }
197
+ .panel { border: round $secondary; border-title-color: $secondary; border-title-style: bold; margin-bottom: 0; padding: 0 1; }
198
+ .panel.active { border: round $primary; border-title-color: $primary; }
199
+ .panel.collapsed { border: none; border-top: round $secondary; height: 1; min-height: 1; padding: 0; }
200
+ #queues { height: 1fr; background: transparent; }
201
+ #status-main { height: 1fr; }
202
+ #records { height: 2fr; }
203
+ #detail-panel { height: 1fr; }
204
+ #detail { width: 1fr; }
205
+ #namespaces { height: 1fr; background: transparent; }
206
+ #namespaces > ListItem { height: 1; }
207
+ .namespace-item-selected { color: $primary; text-style: bold; }
208
+ #namespaces > ListItem.-highlight .namespace-item-selected { color: $block-cursor-foreground; }
209
+ DataTable:focus { border: round $primary; border-title-color: $primary; }
210
+ """
211
+
212
+ def __init__(self) -> None:
213
+ super().__init__()
214
+ self.theme = "dracula"
215
+ self._namespace = loaded_namespace
216
+ self._active_loads: dict[str, int] = {}
217
+ self._load_generation: dict[str, int] = {}
218
+ self._queue_cursors: list[str | None] = [None]
219
+ self._queue_page_index = 0
220
+ self._record_cursors: list[str | None] = [None]
221
+ self._record_page_index = 0
222
+ self._queue: str | None = None
223
+ self._record_kind = "messages"
224
+ self._records: dict[str, Any] = {}
225
+ self._pending: tuple[str, str, str] | None = None
226
+ self._last_refreshed: datetime | None = None
227
+ self._search_query = ""
228
+ self._sidebar_view = "status"
229
+ self._activated_views: set[str] = set()
230
+
231
+ def compose(self) -> ComposeResult:
232
+ with Vertical(id="dashboard"):
233
+ with Horizontal(id="header"):
234
+ yield Static(
235
+ f"[bold]TASKQX[/] · {_connection_label(backend, self._namespace)}",
236
+ id="statusbar",
237
+ )
238
+ yield Static("", id="activity", classes="hidden")
239
+ yield Static(f"v{_TASKQX_VERSION}", id="version")
240
+ with Horizontal(id="layout"):
241
+ with Vertical(id="sidebar"):
242
+ with Vertical(id="status-panel", classes="panel"):
243
+ yield Static("读取中…", id="overall")
244
+ yield Static("等待首个快照", id="refreshed")
245
+ with Vertical(id="namespace-panel", classes="panel"):
246
+ yield ListView(id="namespaces", initial_index=0)
247
+ yield DataTable(
248
+ id="queues",
249
+ classes="panel",
250
+ cursor_type="row",
251
+ zebra_stripes=True,
252
+ )
253
+ with Vertical(id="content"):
254
+ with VerticalScroll(id="status-main", classes="panel"):
255
+ yield Static("诊断信息加载中…", id="status-detail")
256
+ yield DataTable(
257
+ id="records",
258
+ classes="panel",
259
+ cursor_type="row",
260
+ zebra_stripes=True,
261
+ )
262
+ with VerticalScroll(id="detail-panel", classes="panel"):
263
+ yield Static(
264
+ "选择一条记录查看详情;payload 保持脱敏。",
265
+ id="detail",
266
+ )
267
+ yield Footer()
268
+
269
+ def _record_title(self) -> Text:
270
+ return Text(
271
+ {
272
+ "messages": "0-Message",
273
+ "dlq": "0-Dead Letter",
274
+ "eq": "0-Expired Letter",
275
+ }[self._record_kind]
276
+ )
277
+
278
+ def _set_sidebar_layout(self, compact: bool) -> None:
279
+ panels = {
280
+ "status": self.query_one("#status-panel", Vertical),
281
+ "namespaces": self.query_one("#namespace-panel", Vertical),
282
+ "queues": self.query_one("#queues", DataTable),
283
+ }
284
+ content = {
285
+ "status": (
286
+ self.query_one("#overall", Static),
287
+ self.query_one("#refreshed", Static),
288
+ ),
289
+ "namespaces": (self.query_one("#namespaces", ListView),),
290
+ "queues": (),
291
+ }
292
+ for view, panel in panels.items():
293
+ active = view == self._sidebar_view
294
+ collapsed = compact and not active
295
+ panel.set_class(active, "active")
296
+ panel.set_class(collapsed, "collapsed")
297
+ panel.styles.height = "1fr" if active else (1 if compact else None)
298
+ for widget in content[view]:
299
+ widget.styles.display = "none" if collapsed else "block"
300
+
301
+ self.query_one("#records", DataTable).border_title = (
302
+ None if compact else self._record_title()
303
+ )
304
+ self.query_one("#detail-panel", VerticalScroll).border_title = (
305
+ None if compact else Text("Message Detail")
306
+ )
307
+
308
+ def _set_main_view(self, view: str) -> None:
309
+ self._sidebar_view = view
310
+ views = {
311
+ "status": (self.query_one("#status-main", VerticalScroll),),
312
+ "queues": (
313
+ self.query_one("#records", DataTable),
314
+ self.query_one("#detail-panel", VerticalScroll),
315
+ ),
316
+ }
317
+ for name, widgets in views.items():
318
+ for widget in widgets:
319
+ widget.styles.display = "block" if name == view else "none"
320
+ self._set_sidebar_layout(self.size.width < 90 or self.size.height < 30)
321
+
322
+ def on_resize(self, event: Any) -> None:
323
+ """Preserve the active side panel when vertical space is scarce."""
324
+
325
+ layout = self.query_one("#layout", Horizontal)
326
+ sidebar = self.query_one("#sidebar", Vertical)
327
+ content = self.query_one("#content", Vertical)
328
+ narrow = event.size.width < 90
329
+ layout.styles.layout = "vertical" if narrow else "horizontal"
330
+ sidebar.styles.width = "1fr" if narrow else 32
331
+ content.styles.width = "1fr"
332
+ self._set_sidebar_layout(narrow or event.size.height < 30)
333
+
334
+ def on_mount(self) -> None:
335
+ queues = self.query_one("#queues", DataTable)
336
+ status_main = self.query_one("#status-main", VerticalScroll)
337
+ records = self.query_one("#records", DataTable)
338
+ detail_panel = self.query_one("#detail-panel", VerticalScroll)
339
+ self.query_one("#status-panel", Vertical).border_title = Text("1-Status")
340
+ self.query_one("#namespace-panel", Vertical).border_title = Text(
341
+ "2-Namespace"
342
+ )
343
+ queues.border_title = Text("3-Queue")
344
+ status_main.border_title = Text("0-Status")
345
+ records.border_title = self._record_title()
346
+ detail_panel.border_title = Text("Message Detail")
347
+ queues.add_columns(
348
+ ("队列", "queue"),
349
+ ("READY", "ready"),
350
+ ("LEASED", "leased"),
351
+ ("DLQ", "dlq"),
352
+ )
353
+ records.add_column("状态", key="status", width=15)
354
+ records.add_column("消息", key="message", width=32)
355
+ records.add_column("尝试", key="attempt", width=8)
356
+ records.add_column("原因", key="reason", width=38)
357
+ self._set_main_view("status")
358
+ self._load_view_once("status")
359
+
360
+ def _search(self) -> str:
361
+ return self._search_query
362
+
363
+ def _matches(self, *values: object) -> bool:
364
+ query = self._search()
365
+ return not query or any(query in str(value).casefold() for value in values)
366
+
367
+ def _begin_load(self, name: str) -> int:
368
+ generation = self._load_generation.get(name, 0) + 1
369
+ self._load_generation[name] = generation
370
+ self._active_loads[name] = generation
371
+ self._update_activity()
372
+ return generation
373
+
374
+ def _finish_load(self, name: str, generation: int) -> None:
375
+ if self._active_loads.get(name) == generation:
376
+ del self._active_loads[name]
377
+ self._update_activity()
378
+
379
+ def _update_activity(self) -> None:
380
+ activity = self.query_one("#activity", Static)
381
+
382
+ labels = {"status": "状态", "queues": "队列", "records": "消息"}
383
+ if self._active_loads:
384
+ activity.update(
385
+ f"刷新中:{'、'.join(labels[name] for name in self._active_loads)}"
386
+ )
387
+ activity.set_class(not self._active_loads, "hidden")
388
+
389
+ def _load_is_current(self, name: str, generation: int) -> bool:
390
+ return self._load_generation.get(name) == generation
391
+
392
+ async def _load_namespaces(self) -> None:
393
+ namespace_list = self.query_one("#namespaces", ListView)
394
+ if backend == "redis":
395
+ available = await broker.list_namespaces()
396
+ if self._namespace is not None and self._namespace not in available:
397
+ available = tuple(sorted((*available, self._namespace)))
398
+ elif namespace_factory is not None:
399
+ available = tuple(await namespace_factory())
400
+ else:
401
+ available = (self._namespace or "sqlite",)
402
+ selected = self._namespace
403
+ await namespace_list.clear()
404
+ await namespace_list.mount(
405
+ *[
406
+ ListItem(
407
+ Static(
408
+ f"{value} *" if value == selected else value,
409
+ classes="namespace-item-selected"
410
+ if value == selected
411
+ else "",
412
+ ),
413
+ name=value,
414
+ )
415
+ for value in available
416
+ ]
417
+ )
418
+ if selected in available:
419
+ namespace_list.index = available.index(selected)
420
+
421
+ def _schedule_queues(self) -> None:
422
+ self.run_worker(
423
+ self._load_queues(),
424
+ group="queue-refresh",
425
+ exclusive=True,
426
+ exit_on_error=False,
427
+ )
428
+
429
+ def _schedule_records(self) -> None:
430
+ self.run_worker(
431
+ self._load_records(),
432
+ group="record-refresh",
433
+ exclusive=True,
434
+ exit_on_error=False,
435
+ )
436
+
437
+ async def _load_queues(self) -> None:
438
+ generation = self._begin_load("queues")
439
+ try:
440
+ page = await broker.list_queues(
441
+ cursor=self._queue_cursors[self._queue_page_index],
442
+ limit=self.PAGE_SIZE,
443
+ )
444
+ table = self.query_one("#queues", DataTable)
445
+ table.clear()
446
+ visible = [item for item in page.items if self._matches(item.queue)]
447
+ for item in visible:
448
+ table.add_row(
449
+ item.queue,
450
+ str(item.ready),
451
+ str(item.leased),
452
+ str(item.dead_letters),
453
+ key=item.queue,
454
+ )
455
+ if page.next_cursor is not None:
456
+ self._queue_cursors = self._queue_cursors[
457
+ : self._queue_page_index + 1
458
+ ] + [page.next_cursor]
459
+ else:
460
+ self._queue_cursors = self._queue_cursors[
461
+ : self._queue_page_index + 1
462
+ ]
463
+ except Exception as exc: # noqa: BLE001 - backend failures are operator-visible
464
+ self.notify(
465
+ f"队列加载失败:{type(exc).__name__}: {exc};按 r 重试。",
466
+ severity="error",
467
+ )
468
+ finally:
469
+ self._finish_load("queues", generation)
470
+
471
+ async def _load_records(self) -> None:
472
+ generation = self._begin_load("records")
473
+ try:
474
+ if self._queue is None:
475
+ table = self.query_one("#records", DataTable)
476
+ table.clear()
477
+ self._records.clear()
478
+ return
479
+ cursor = self._record_cursors[self._record_page_index]
480
+ if self._record_kind == "messages":
481
+ page = await broker.list_message_summaries(
482
+ self._queue, cursor=cursor, limit=self.PAGE_SIZE
483
+ )
484
+ rows = [
485
+ (
486
+ item.message_id,
487
+ item.status.value.upper(),
488
+ item.attempt,
489
+ item.last_reason or "—",
490
+ item,
491
+ )
492
+ for item in page.items
493
+ ]
494
+ elif self._record_kind == "dlq":
495
+ page = await broker.admin.page_dead_letters(
496
+ self._queue, cursor=cursor, limit=self.PAGE_SIZE
497
+ )
498
+ rows = [
499
+ (
500
+ item.message.id,
501
+ "DEAD_LETTERED",
502
+ item.attempt,
503
+ item.reason,
504
+ item,
505
+ )
506
+ for item in page.items
507
+ ]
508
+ else:
509
+ page = await broker.admin.page_expired(
510
+ self._queue, cursor=cursor, limit=self.PAGE_SIZE
511
+ )
512
+ rows = [
513
+ (item.message.id, "EXPIRED", item.attempt, "expired", item)
514
+ for item in page.items
515
+ ]
516
+ if not self._load_is_current("records", generation):
517
+ return
518
+ table = self.query_one("#records", DataTable)
519
+ table.clear()
520
+ seen_message_ids: set[str] = set()
521
+ for message_id, status, attempt, reason, item in rows:
522
+ if message_id in seen_message_ids:
523
+ continue
524
+ seen_message_ids.add(message_id)
525
+ if self._matches(message_id, status, reason):
526
+ rendered_status = Text(status)
527
+ rendered_status.stylize(
528
+ {
529
+ "READY": "green",
530
+ "LEASED": "yellow",
531
+ "DEAD_LETTERED": "red",
532
+ "EXPIRED": "magenta",
533
+ }.get(status, "cyan"),
534
+ 0,
535
+ 1,
536
+ )
537
+ table.add_row(
538
+ rendered_status,
539
+ _truncate(message_id, 29),
540
+ str(attempt),
541
+ _truncate(reason, 35),
542
+ key=message_id,
543
+ )
544
+ self._records[message_id] = item
545
+ if page.next_cursor is not None:
546
+ self._record_cursors = self._record_cursors[
547
+ : self._record_page_index + 1
548
+ ] + [page.next_cursor]
549
+ else:
550
+ self._record_cursors = self._record_cursors[
551
+ : self._record_page_index + 1
552
+ ]
553
+ except Exception as exc: # noqa: BLE001 - backend failures are operator-visible
554
+ self.notify(
555
+ f"消息加载失败:{type(exc).__name__}: {exc};按 r 重试。",
556
+ severity="error",
557
+ )
558
+ finally:
559
+ self._finish_load("records", generation)
560
+
561
+ def _load_view_once(self, view: str) -> None:
562
+ if view in self._activated_views:
563
+ return
564
+ self._activated_views.add(view)
565
+ self.action_refresh(load_queues=view == "queues")
566
+
567
+ def action_refresh(self, *, load_queues: bool | None = None) -> None:
568
+ if load_queues is None:
569
+ load_queues = "queues" in self._activated_views
570
+ self.run_worker(
571
+ self._refresh_status(),
572
+ group="status-refresh",
573
+ exclusive=True,
574
+ exit_on_error=False,
575
+ )
576
+ if load_queues:
577
+ self._schedule_queues()
578
+
579
+ async def _refresh_status(self) -> None:
580
+ generation = self._begin_load("status")
581
+ try:
582
+ report, _ = await asyncio.gather(
583
+ broker.health_check(), self._load_namespaces()
584
+ )
585
+ self._last_refreshed = datetime.now().astimezone()
586
+ state = "HEALTHY" if report.healthy else "ATTENTION REQUIRED"
587
+ timestamp = f"{self._last_refreshed:%Y-%m-%d %H:%M:%S %Z}"
588
+ self.query_one("#overall", Static).update(
589
+ f"[bold]整体状态[/]\n{state}\n[dim]{len(report.checks)} 项诊断[/]"
590
+ )
591
+ self.query_one("#refreshed", Static).update(f"已刷新 {timestamp}")
592
+ self.query_one("#status-detail", Static).update(
593
+ f"[bold]状态[/] {state}\n刷新时间: {timestamp}\n\n"
594
+ f"{_render_health_diagnostics(report)}"
595
+ )
596
+ except Exception as exc: # noqa: BLE001 - backend diagnostics are operator-visible
597
+ self.query_one("#overall", Static).update(
598
+ f"[bold]整体状态[/]\nREFRESH FAILED\n[dim]{type(exc).__name__}[/]"
599
+ )
600
+ self.query_one("#status-detail", Static).update(
601
+ f"[bold]刷新失败[/]\n{type(exc).__name__}: {exc}"
602
+ )
603
+ self.notify(
604
+ f"刷新失败:{type(exc).__name__}: {exc};检查连接后按 r 重试。",
605
+ severity="error",
606
+ )
607
+ finally:
608
+ self._finish_load("status", generation)
609
+
610
+ def action_main(self) -> None:
611
+ if self._sidebar_view == "queues":
612
+ self.query_one("#records", DataTable).focus()
613
+ else:
614
+ self._set_main_view("status")
615
+ self.query_one("#status-main", VerticalScroll).focus()
616
+
617
+ def action_status(self) -> None:
618
+ self._set_main_view("status")
619
+ self._load_view_once("status")
620
+
621
+ def action_namespaces(self) -> None:
622
+ self._sidebar_view = "namespaces"
623
+ self._set_sidebar_layout(self.size.width < 90 or self.size.height < 30)
624
+ self.query_one("#namespaces", ListView).focus()
625
+
626
+ def action_queues(self) -> None:
627
+ self._set_main_view("queues")
628
+ self.query_one("#queues", DataTable).focus()
629
+ self._load_view_once("queues")
630
+
631
+ async def on_list_view_selected(self, event: Any) -> None:
632
+ selected = event.item.name
633
+ if not selected:
634
+ return
635
+ if selected != self._namespace:
636
+ if backend != "redis" or not hasattr(broker, "select_namespace"):
637
+ self.notify("当前 backend 不支持切换 namespace。", severity="warning")
638
+ return
639
+ broker.select_namespace(selected)
640
+ self._namespace = selected
641
+ self._queue = None
642
+ self._queue_cursors = [None]
643
+ self._queue_page_index = 0
644
+ self._record_cursors = [None]
645
+ self._record_page_index = 0
646
+ self.query_one("#queues", DataTable).clear()
647
+ self.query_one("#detail", Static).update(
648
+ "选择一条记录查看详情;payload 保持脱敏。"
649
+ )
650
+ self._records.clear()
651
+ self.query_one("#records", DataTable).clear()
652
+ self.query_one("#statusbar", Static).update(
653
+ f"[bold]TASKQX[/] · {_connection_label(backend, self._namespace)}"
654
+ )
655
+ self._activated_views.add("queues")
656
+ self.action_refresh(load_queues=True)
657
+
658
+ def _switch_records(self, kind: str) -> None:
659
+ self._record_kind = kind
660
+ self._record_cursors = [None]
661
+ self._record_page_index = 0
662
+ self._schedule_records()
663
+
664
+ def action_messages(self) -> None:
665
+ self._switch_records("messages")
666
+
667
+ def action_dead_letters(self) -> None:
668
+ self._switch_records("dlq")
669
+
670
+ def action_expired(self) -> None:
671
+ self._switch_records("eq")
672
+
673
+ def action_next_page(self) -> None:
674
+ if self._record_cursors and self._record_page_index + 1 < len(
675
+ self._record_cursors
676
+ ):
677
+ self._record_page_index += 1
678
+ self._schedule_records()
679
+ elif self._queue_cursors and self._queue_page_index + 1 < len(
680
+ self._queue_cursors
681
+ ):
682
+ self._queue_page_index += 1
683
+ self._schedule_queues()
684
+
685
+ def action_previous_page(self) -> None:
686
+ if self._record_page_index:
687
+ self._record_page_index -= 1
688
+ self._schedule_records()
689
+ elif self._queue_page_index:
690
+ self._queue_page_index -= 1
691
+ self._schedule_queues()
692
+
693
+ def _selected(self) -> tuple[str, Any] | None:
694
+ table = self.query_one("#records", DataTable)
695
+ if table.cursor_row is None or table.row_count == 0:
696
+ return None
697
+ row_key, _ = table.coordinate_to_cell_key(table.cursor_coordinate)
698
+ message_id = str(row_key.value)
699
+ item = self._records.get(message_id)
700
+ return (message_id, item) if item is not None else None
701
+
702
+ def _detail(
703
+ self,
704
+ item: Any,
705
+ *,
706
+ message: Any | None = None,
707
+ include_payload: bool = False,
708
+ ) -> Text:
709
+ message_id = getattr(item, "message_id", None) or item.message.id
710
+ created_at = getattr(item, "created_at", None) or item.message.created_at
711
+ serializer_name = (
712
+ getattr(item, "serializer_name", None)
713
+ or getattr(item.message, "payload_schema_name", None)
714
+ or "json"
715
+ )
716
+ serializer_version = (
717
+ getattr(item, "serializer_version", None)
718
+ or getattr(item.message, "payload_schema_version", None)
719
+ or "—"
720
+ )
721
+ status = getattr(item, "status", self._record_kind)
722
+ status_value = str(getattr(status, "value", status)).upper()
723
+ payload = (
724
+ message.payload
725
+ if include_payload and message is not None
726
+ else "<permanently pruned>"
727
+ if getattr(item, "payload_pruned", False)
728
+ else "<redacted>"
729
+ )
730
+ reason = (
731
+ getattr(item, "last_reason", None)
732
+ or getattr(item, "reason", None)
733
+ or "—"
734
+ )
735
+ workflow_id = getattr(item, "workflow_id", None)
736
+ parent_id = getattr(item, "parent_id", None)
737
+ lineage = " · ".join(
738
+ part
739
+ for part in (
740
+ f"workflow: {workflow_id}" if workflow_id else None,
741
+ f"parent: {parent_id}" if parent_id else None,
742
+ )
743
+ if part is not None
744
+ ) or "—"
745
+ acked_at = getattr(item, "acked_at", None)
746
+ acknowledged = acked_at.isoformat() if acked_at is not None else "—"
747
+ return Text.assemble(
748
+ ("消息", "bold"),
749
+ f" {message_id}\n状态: {status_value} · 尝试: {item.attempt} · 原因: {reason}\n"
750
+ f"创建: {created_at.isoformat()} · 确认: {acknowledged}\n"
751
+ f"serializer: {serializer_name}@{serializer_version} · lineage: {lineage}\n"
752
+ f"payload: {payload}",
753
+ )
754
+
755
+ def _open_command(self, placeholder: str | None = None) -> None:
756
+ self.push_screen(
757
+ TextInputModal("命令", placeholder or "输入命令后按 Enter 执行…"),
758
+ self._submit_command,
759
+ )
760
+
761
+ def _submit_command(self, value: str | None) -> None:
762
+ if value is not None:
763
+ self.run_worker(self._run_command(value.strip()))
764
+
765
+ def action_search(self) -> None:
766
+ self.push_screen(
767
+ TextInputModal("搜索", "筛选当前页的队列或消息,按 Enter 应用…"),
768
+ self._submit_search,
769
+ )
770
+
771
+ def _submit_search(self, value: str | None) -> None:
772
+ if value is not None:
773
+ self._search_query = value.casefold().strip()
774
+ self._reload_search_results()
775
+
776
+ def _reload_search_results(self) -> None:
777
+ if self._sidebar_view != "queues":
778
+ return
779
+ self._schedule_queues()
780
+ self.query_one("#records", DataTable).focus()
781
+
782
+ def action_show_payload(self) -> None:
783
+ selected = self._selected()
784
+ if selected is None:
785
+ self.notify("请先选择一条消息。", severity="warning")
786
+ return
787
+ self.run_worker(self._show_payload(selected))
788
+
789
+ async def _show_payload(self, selected: tuple[str, Any]) -> None:
790
+ message = await broker.observe_message(selected[0])
791
+ if message is None:
792
+ if getattr(selected[1], "payload_pruned", False):
793
+ self.notify("业务内容已按 ACK 保留期永久清除。", severity="warning")
794
+ else:
795
+ self.notify("消息已不存在,请刷新列表。", severity="warning")
796
+ return
797
+ self.query_one("#detail", Static).update(
798
+ self._detail(selected[1], message=message, include_payload=True)
799
+ )
800
+
801
+ def _select_queue(self, event: Any) -> None:
802
+ if event.row_key is None:
803
+ return
804
+ self._queue = str(event.row_key.value)
805
+ self._record_cursors = [None]
806
+ self._record_page_index = 0
807
+ self._records.clear()
808
+ self._schedule_records()
809
+
810
+ def _update_record_detail(self) -> None:
811
+ selected = self._selected()
812
+ if selected is not None:
813
+ self.query_one("#detail", Static).update(self._detail(selected[1]))
814
+
815
+ def on_data_table_row_selected(self, event: Any) -> None:
816
+ if event.data_table.id == "queues":
817
+ self._select_queue(event)
818
+ elif event.data_table.id == "records":
819
+ self._update_record_detail()
820
+
821
+ def on_data_table_row_highlighted(self, event: Any) -> None:
822
+ if event.data_table.id == "records":
823
+ self._update_record_detail()
824
+
825
+ def action_command(self) -> None:
826
+ self._open_command()
827
+
828
+ async def _run_command(self, command: str) -> None:
829
+ if command in {"refresh", "r"}:
830
+ self.action_refresh()
831
+ elif command in {"messages", "m"}:
832
+ self.action_messages()
833
+ elif command in {"dlq", "d"}:
834
+ self.action_dead_letters()
835
+ elif command in {"eq", "e"}:
836
+ self.action_expired()
837
+ elif command in {"next", "n"}:
838
+ self.action_next_page()
839
+ elif command in {"prev", "p"}:
840
+ self.action_previous_page()
841
+ else:
842
+ self.notify(
843
+ "未知命令;可用:refresh、messages、dlq、eq、next、prev。",
844
+ severity="warning",
845
+ )
846
+
847
+ def _queue_is_focused(self) -> bool:
848
+ return self.focused is self.query_one("#queues", DataTable)
849
+
850
+ def _request_confirmation(
851
+ self,
852
+ operation: str,
853
+ kind: str,
854
+ target: str,
855
+ title: str,
856
+ description: str,
857
+ ) -> None:
858
+ self._pending = (operation, kind, target)
859
+ self.push_screen(
860
+ ConfirmModal(title, description), self._resolve_confirmation
861
+ )
862
+
863
+ def _resolve_confirmation(self, confirmed: bool | None) -> None:
864
+ if confirmed:
865
+ self.run_worker(self._confirm_pending())
866
+ else:
867
+ self._pending = None
868
+
869
+ def action_replay(self) -> None:
870
+ if self._queue_is_focused():
871
+ if self._queue is None:
872
+ self.notify("请先选择一个队列。", severity="warning")
873
+ return
874
+ self._request_confirmation(
875
+ "replay_queue",
876
+ "queue",
877
+ self._queue,
878
+ "重放队列",
879
+ f"来源: {self._queue} 的 DLQ/EQ · 目标: {self._queue} · dedup: keep\n"
880
+ "将重新入队该队列全部 DLQ 与 EQ 消息。",
881
+ )
882
+ return
883
+ selected = self._selected()
884
+ if (
885
+ selected is None
886
+ or self._record_kind not in {"dlq", "eq"}
887
+ or self._queue is None
888
+ ):
889
+ self.notify("仅能重放已选择的 DLQ/EQ 消息。", severity="warning")
890
+ return
891
+ message_id, _ = selected
892
+ self._request_confirmation(
893
+ "replay",
894
+ self._record_kind,
895
+ message_id,
896
+ "重放消息",
897
+ f"来源: {self._record_kind.upper()} · 目标: {self._queue} · dedup: keep\n"
898
+ f"将消息 {message_id} 重新入队。",
899
+ )
900
+
901
+ def action_delete_record(self) -> None:
902
+ if self._queue_is_focused():
903
+ if self._queue is None:
904
+ self.notify("请先选择一个队列。", severity="warning")
905
+ return
906
+ self._request_confirmation(
907
+ "delete_queue",
908
+ "queue",
909
+ self._queue,
910
+ "删除队列",
911
+ f"将永久删除队列 {self._queue} 的全部消息、DLQ、EQ 和 dedup 状态。",
912
+ )
913
+ return
914
+ selected = self._selected()
915
+ if (
916
+ selected is None
917
+ or self._record_kind not in {"dlq", "eq"}
918
+ or self._queue is None
919
+ ):
920
+ self.notify("仅能删除已选择的 DLQ/EQ 消息。", severity="warning")
921
+ return
922
+ message_id, _ = selected
923
+ self._request_confirmation(
924
+ "delete",
925
+ self._record_kind,
926
+ message_id,
927
+ "删除消息",
928
+ f"来源: {self._record_kind.upper()} · 目标: {self._queue}\n"
929
+ f"将永久删除消息 {message_id}。",
930
+ )
931
+
932
+ def action_consistency_repair(self) -> None:
933
+ if self._queue is None:
934
+ self.notify("请先选择一个队列。", severity="warning")
935
+ return
936
+ self.run_worker(self._preview_consistency_repair(self._queue))
937
+
938
+ async def _preview_consistency_repair(self, queue: str) -> None:
939
+ try:
940
+ proposal = await broker.repair_consistency(queue)
941
+ except Exception as exc: # noqa: BLE001 - backend failures are operator-visible
942
+ self.notify(
943
+ f"一致性检查失败:{type(exc).__name__}: {exc};请检查状态后重试。",
944
+ severity="error",
945
+ )
946
+ return
947
+ self._request_confirmation(
948
+ "repair",
949
+ "consistency",
950
+ queue,
951
+ "修复队列一致性",
952
+ f"dry-run 发现 {len(proposal.repairs)} 项待修复;确认后将应用队列 {queue} 的修复。",
953
+ )
954
+
955
+ async def _confirm_pending(self) -> None:
956
+ assert self._pending is not None
957
+ operation, kind, target = self._pending
958
+ try:
959
+ if operation == "repair":
960
+ await broker.repair_consistency(target, dry_run=False)
961
+ self.notify("一致性修复已应用。")
962
+ elif operation == "replay_queue":
963
+ dead_letters, expired = await asyncio.gather(
964
+ broker.admin.list_dead_letters(target),
965
+ broker.admin.list_expired(target),
966
+ )
967
+ for item in dead_letters:
968
+ await broker.admin.replay_dead_letter(
969
+ target, item.message.id, dedup_mode="keep"
970
+ )
971
+ for item in expired:
972
+ await broker.admin.replay_expired(
973
+ target,
974
+ item.message.id,
975
+ expires_at=None,
976
+ dedup_mode="keep",
977
+ )
978
+ self._record_kind = "messages"
979
+ self._record_cursors = [None]
980
+ self._record_page_index = 0
981
+ self.notify(
982
+ f"已重新入队 {len(dead_letters) + len(expired)} 条消息;业务 handler 将异步处理。"
983
+ )
984
+ elif operation == "delete_queue":
985
+ deleted = await broker.admin.delete_queue(target)
986
+ self._queue = None
987
+ self._records.clear()
988
+ self.query_one("#records", DataTable).clear()
989
+ self.notify(f"队列已删除({deleted} 条消息)。")
990
+ await self._load_queues()
991
+ return
992
+ elif operation == "replay":
993
+ assert self._queue is not None
994
+ if kind == "dlq":
995
+ await broker.admin.replay_dead_letter(
996
+ self._queue, target, dedup_mode="keep"
997
+ )
998
+ else:
999
+ await broker.admin.replay_expired(
1000
+ self._queue,
1001
+ target,
1002
+ expires_at=None,
1003
+ dedup_mode="keep",
1004
+ )
1005
+ self._record_kind = "messages"
1006
+ self._record_cursors = [None]
1007
+ self._record_page_index = 0
1008
+ self.notify("消息已重新入队;业务 handler 将异步处理。")
1009
+ elif kind == "dlq":
1010
+ assert self._queue is not None
1011
+ await broker.admin.delete_dead_letter(self._queue, target)
1012
+ self.notify("DLQ 消息已删除。")
1013
+ else:
1014
+ assert self._queue is not None
1015
+ await broker.admin.delete_expired(self._queue, target)
1016
+ self.notify("EQ 消息已删除。")
1017
+ await self._load_records()
1018
+ except Exception as exc: # noqa: BLE001
1019
+ self.notify(
1020
+ f"操作失败:{type(exc).__name__}: {exc};请检查状态后重试。",
1021
+ severity="error",
1022
+ )
1023
+ finally:
1024
+ self._pending = None
1025
+
1026
+ def action_help(self) -> None:
1027
+ self.push_screen(HelpModal())
1028
+
1029
+ return OperationsApp()
1030
+
1031
+
1032
+ async def run_tui(
1033
+ broker: Any,
1034
+ *,
1035
+ backend: str,
1036
+ namespace: str | None,
1037
+ namespace_factory: Any | None = None,
1038
+ ) -> int:
1039
+ """Run the Textual dashboard."""
1040
+
1041
+ app = build_tui_app(
1042
+ broker,
1043
+ backend=backend,
1044
+ namespace=namespace,
1045
+ namespace_factory=namespace_factory,
1046
+ )
1047
+ await app.run_async()
1048
+ return 0