networka 0.1.9__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 (93) hide show
  1. network_toolkit/__about__.py +4 -0
  2. network_toolkit/__init__.py +8 -0
  3. network_toolkit/__main__.py +10 -0
  4. network_toolkit/builtin_sequences/arista_eos/common.yml +53 -0
  5. network_toolkit/builtin_sequences/mikrotik_routeros/common.yml +52 -0
  6. network_toolkit/cli.py +265 -0
  7. network_toolkit/commands/__init__.py +8 -0
  8. network_toolkit/commands/backup.py +441 -0
  9. network_toolkit/commands/complete.py +172 -0
  10. network_toolkit/commands/config.py +1068 -0
  11. network_toolkit/commands/diff.py +485 -0
  12. network_toolkit/commands/download.py +197 -0
  13. network_toolkit/commands/firmware.py +780 -0
  14. network_toolkit/commands/info.py +377 -0
  15. network_toolkit/commands/list.py +345 -0
  16. network_toolkit/commands/routerboard_upgrade.py +204 -0
  17. network_toolkit/commands/run.py +839 -0
  18. network_toolkit/commands/schema_unified.py +91 -0
  19. network_toolkit/commands/sequence.py +17 -0
  20. network_toolkit/commands/ssh.py +540 -0
  21. network_toolkit/commands/ssh_engines.py +0 -0
  22. network_toolkit/commands/ssh_fallback.py +97 -0
  23. network_toolkit/commands/ssh_platform.py +120 -0
  24. network_toolkit/commands/upload.py +237 -0
  25. network_toolkit/commands/vendor_config_backup.py +378 -0
  26. network_toolkit/common/color_magic.py +177 -0
  27. network_toolkit/common/command.py +135 -0
  28. network_toolkit/common/command_base.py +135 -0
  29. network_toolkit/common/command_helpers.py +214 -0
  30. network_toolkit/common/credentials.py +86 -0
  31. network_toolkit/common/defaults.py +17 -0
  32. network_toolkit/common/errors.py +130 -0
  33. network_toolkit/common/interactive_confirmation.py +144 -0
  34. network_toolkit/common/logging.py +47 -0
  35. network_toolkit/common/output.py +594 -0
  36. network_toolkit/common/output_clean.py +244 -0
  37. network_toolkit/common/paths.py +86 -0
  38. network_toolkit/common/resolver.py +207 -0
  39. network_toolkit/common/styles.py +199 -0
  40. network_toolkit/common/table_generator.py +169 -0
  41. network_toolkit/common/table_providers.py +716 -0
  42. network_toolkit/config.py +1506 -0
  43. network_toolkit/credentials.py +288 -0
  44. network_toolkit/device.py +1658 -0
  45. network_toolkit/device_transfers.py +170 -0
  46. network_toolkit/exceptions.py +78 -0
  47. network_toolkit/ip_device.py +241 -0
  48. network_toolkit/platforms/__init__.py +21 -0
  49. network_toolkit/platforms/base.py +267 -0
  50. network_toolkit/platforms/cisco_ios/__init__.py +6 -0
  51. network_toolkit/platforms/cisco_ios/constants.py +15 -0
  52. network_toolkit/platforms/cisco_ios/operations.py +426 -0
  53. network_toolkit/platforms/cisco_iosxe/__init__.py +6 -0
  54. network_toolkit/platforms/cisco_iosxe/constants.py +15 -0
  55. network_toolkit/platforms/cisco_iosxe/operations.py +580 -0
  56. network_toolkit/platforms/cisco_shared/__init__.py +0 -0
  57. network_toolkit/platforms/cisco_shared/operations.py +0 -0
  58. network_toolkit/platforms/factory.py +190 -0
  59. network_toolkit/platforms/mikrotik_routeros/__init__.py +8 -0
  60. network_toolkit/platforms/mikrotik_routeros/confirmation_patterns.py +24 -0
  61. network_toolkit/platforms/mikrotik_routeros/constants.py +31 -0
  62. network_toolkit/platforms/mikrotik_routeros/operations.py +686 -0
  63. network_toolkit/results_enhanced.py +364 -0
  64. network_toolkit/schemas/__init__.py +8 -0
  65. network_toolkit/sequence_manager.py +239 -0
  66. network_toolkit/shell_completion/bash_completion_nw.sh +339 -0
  67. network_toolkit/shell_completion/zsh_completion_nw.zsh +136 -0
  68. network_toolkit/transport/__init__.py +15 -0
  69. network_toolkit/transport/factory.py +113 -0
  70. network_toolkit/transport/interfaces.py +46 -0
  71. network_toolkit/transport/nornir_inventory.py +173 -0
  72. network_toolkit/transport/nornir_netmiko.py +277 -0
  73. network_toolkit/transport/scrapli_sync.py +36 -0
  74. network_toolkit/tui/__init__.py +18 -0
  75. network_toolkit/tui/app.py +1275 -0
  76. network_toolkit/tui/clipboard.py +46 -0
  77. network_toolkit/tui/compat.py +111 -0
  78. network_toolkit/tui/constants.py +111 -0
  79. network_toolkit/tui/controller.py +550 -0
  80. network_toolkit/tui/data.py +149 -0
  81. network_toolkit/tui/dialogs.py +196 -0
  82. network_toolkit/tui/helpers.py +55 -0
  83. network_toolkit/tui/keymap.py +31 -0
  84. network_toolkit/tui/layout.py +111 -0
  85. network_toolkit/tui/models.py +93 -0
  86. network_toolkit/tui/output_manager.py +372 -0
  87. network_toolkit/tui/prompt.py +172 -0
  88. network_toolkit/tui/services.py +285 -0
  89. networka-0.1.9.dist-info/METADATA +316 -0
  90. networka-0.1.9.dist-info/RECORD +93 -0
  91. networka-0.1.9.dist-info/WHEEL +4 -0
  92. networka-0.1.9.dist-info/entry_points.txt +2 -0
  93. networka-0.1.9.dist-info/licenses/LICENSE +73 -0
@@ -0,0 +1,196 @@
1
+ """Small reusable modal dialogs for the TUI.
2
+
3
+ These utilities import Textual lazily and return False when a dialog cannot be
4
+ shown (e.g., Textual not installed). Callers should provide a fallback.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ # pyright: reportUnknownArgumentType=false, reportUnknownMemberType=false, reportUnknownVariableType=false, reportGeneralTypeIssues=false
10
+ from collections.abc import Callable
11
+ from typing import Any, Literal
12
+
13
+ try: # Optional at import time; provide stubs if unavailable
14
+ from textual.containers import Vertical as _Vertical # type: ignore
15
+ from textual.screen import ModalScreen as _ModalScreenBase # type: ignore
16
+ from textual.widgets import Button as _Button # type: ignore
17
+ from textual.widgets import Static as _Static # type: ignore
18
+ except Exception: # pragma: no cover - textual not installed
19
+ _ModalScreenBase = object # type: ignore
20
+
21
+ class _Button: # type: ignore
22
+ def __init__(self, *args: Any, **kwargs: Any) -> None: ...
23
+
24
+ class _Static: # type: ignore
25
+ def __init__(self, *args: Any, **kwargs: Any) -> None: ...
26
+
27
+ class _Vertical: # type: ignore
28
+ def __init__(self, *args: Any, **kwargs: Any) -> None: ...
29
+
30
+ def __enter__(self) -> Any: # Return Any to match imported Vertical
31
+ return self
32
+
33
+ def __exit__(self, *_: Any) -> Literal[False]:
34
+ return False
35
+
36
+
37
+ class _ConfirmDialog(_ModalScreenBase): # type: ignore[misc]
38
+ DEFAULT_CSS = (
39
+ "#nw-dialog { width: 70; border: round $surface; padding: 1 2; }\n"
40
+ "#nw-dialog Static.title { content-align: center middle; text-style: bold; }\n"
41
+ "#nw-dialog .buttons { content-align: center middle; height: 3; }\n"
42
+ )
43
+
44
+ def __init__(
45
+ self, message: str, on_yes: Callable[[], None], on_no: Callable[[], None]
46
+ ) -> None:
47
+ super().__init__() # type: ignore[misc]
48
+ self._message = message
49
+ self._on_yes = on_yes
50
+ self._on_no = on_no
51
+
52
+ def compose(self) -> Any:
53
+ with _Vertical(id="nw-dialog"): # type: ignore[misc]
54
+ yield _Static(self._message, classes="title")
55
+ with _Vertical(classes="buttons"): # type: ignore[misc]
56
+ yield _Button("Yes [y]", id="btn-yes")
57
+ yield _Button("No [N]/Esc", id="btn-no")
58
+
59
+ def on_button_pressed(self, event: Any) -> None:
60
+ bid = getattr(getattr(event, "button", None), "id", "")
61
+ if bid == "btn-yes":
62
+ self._on_yes()
63
+ try:
64
+ self.dismiss(None) # type: ignore[call-arg]
65
+ except Exception:
66
+ pass
67
+ elif bid == "btn-no":
68
+ self._on_no()
69
+ try:
70
+ self.dismiss(None) # type: ignore[call-arg]
71
+ except Exception:
72
+ pass
73
+
74
+ def on_key(self, event: Any) -> None:
75
+ key = str(getattr(event, "key", "")).lower()
76
+ if key in {"y"}:
77
+ self._on_yes()
78
+ try:
79
+ self.dismiss(None) # type: ignore[call-arg]
80
+ except Exception:
81
+ pass
82
+ elif key in {"n", "escape", "enter", "return"}:
83
+ self._on_no()
84
+ try:
85
+ self.dismiss(None) # type: ignore[call-arg]
86
+ except Exception:
87
+ pass
88
+
89
+
90
+ class _CancelModeDialog(_ModalScreenBase): # type: ignore[misc]
91
+ DEFAULT_CSS = (
92
+ "#nw-dialog { width: 70; border: round $surface; padding: 1 2; }\n"
93
+ "#nw-dialog Static.title { content-align: center middle; text-style: bold; }\n"
94
+ "#nw-dialog .buttons { content-align: center middle; height: 3; }\n"
95
+ )
96
+
97
+ def __init__(
98
+ self,
99
+ on_soft: Callable[[], None],
100
+ on_hard: Callable[[], None],
101
+ on_abort: Callable[[], None],
102
+ ) -> None:
103
+ super().__init__() # type: ignore[misc]
104
+ self._on_soft = on_soft
105
+ self._on_hard = on_hard
106
+ self._on_abort = on_abort
107
+
108
+ def compose(self) -> Any:
109
+ with _Vertical(id="nw-dialog"): # type: ignore[misc]
110
+ yield _Static(
111
+ "Cancel type? Soft [s] (recommended) or Hard [h]. Hard will close sessions immediately and may leave devices in a partial state.",
112
+ classes="title",
113
+ )
114
+ with _Vertical(classes="buttons"): # type: ignore[misc]
115
+ yield _Button("Soft cancel [s]", id="btn-soft")
116
+ yield _Button("Hard cancel [h] (disconnect sessions)", id="btn-hard")
117
+ yield _Button("Keep running [N]/Esc", id="btn-no")
118
+
119
+ def on_button_pressed(self, event: Any) -> None:
120
+ bid = getattr(getattr(event, "button", None), "id", "")
121
+ if bid == "btn-soft":
122
+ self._on_soft()
123
+ try:
124
+ self.dismiss(None) # type: ignore[call-arg]
125
+ except Exception:
126
+ pass
127
+ elif bid == "btn-hard":
128
+ self._on_hard()
129
+ try:
130
+ self.dismiss(None) # type: ignore[call-arg]
131
+ except Exception:
132
+ pass
133
+ elif bid == "btn-no":
134
+ self._on_abort()
135
+ try:
136
+ self.dismiss(None) # type: ignore[call-arg]
137
+ except Exception:
138
+ pass
139
+
140
+ def on_key(self, event: Any) -> None:
141
+ key = str(getattr(event, "key", "")).lower()
142
+ if key in {"s", "enter", "return"}:
143
+ self._on_soft()
144
+ try:
145
+ self.dismiss(None) # type: ignore[call-arg]
146
+ except Exception:
147
+ pass
148
+ elif key == "h":
149
+ self._on_hard()
150
+ try:
151
+ self.dismiss(None) # type: ignore[call-arg]
152
+ except Exception:
153
+ pass
154
+ elif key in {"n", "escape"}:
155
+ self._on_abort()
156
+ try:
157
+ self.dismiss(None) # type: ignore[call-arg]
158
+ except Exception:
159
+ pass
160
+
161
+
162
+ def show_confirm_dialog(
163
+ app: Any,
164
+ message: str,
165
+ *,
166
+ on_yes: Callable[[], None],
167
+ on_no: Callable[[], None],
168
+ ) -> bool:
169
+ """Show a simple Yes/No modal confirmation dialog.
170
+
171
+ Returns True if a dialog was shown; False if Textual isn't available.
172
+ """
173
+ # If ModalScreen is not available, bail out so caller can fallback
174
+ if _ModalScreenBase is object:
175
+ return False
176
+ try:
177
+ app.push_screen(_ConfirmDialog(message, on_yes, on_no))
178
+ return True
179
+ except Exception:
180
+ return False
181
+
182
+
183
+ def show_cancel_mode_dialog(
184
+ app: Any,
185
+ *,
186
+ on_soft: Callable[[], None],
187
+ on_hard: Callable[[], None],
188
+ on_abort: Callable[[], None],
189
+ ) -> bool:
190
+ if _ModalScreenBase is object:
191
+ return False
192
+ try:
193
+ app.push_screen(_CancelModeDialog(on_soft, on_hard, on_abort))
194
+ return True
195
+ except Exception:
196
+ return False
@@ -0,0 +1,55 @@
1
+ """Helper utilities for the Textual UI.
2
+
3
+ This module contains small, UI-adjacent helpers that don't require importing
4
+ Textual at module import time. Keep dependencies minimal.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Iterable
10
+ from typing import Any
11
+
12
+ try: # optional rich
13
+ from rich.markup import escape as _escape_markup
14
+ except Exception: # pragma: no cover - rich optional
15
+ _escape_markup = None # type: ignore[assignment]
16
+
17
+
18
+ def log_write(log_widget: Any, message: str) -> None:
19
+ """Best-effort write to a Textual Log/RichLog-like widget.
20
+
21
+ Accepts multiple widget API shapes across Textual versions.
22
+ """
23
+ try:
24
+ msg = str(message)
25
+ # Escape markup if the widget interprets Rich markup to avoid injection
26
+ if _escape_markup is not None:
27
+ msg = _escape_markup(msg)
28
+ if hasattr(log_widget, "write"):
29
+ log_widget.write(msg)
30
+ elif hasattr(log_widget, "write_line"):
31
+ log_widget.write_line(msg)
32
+ elif hasattr(log_widget, "update"):
33
+ # Fallback: append to existing content if possible
34
+ try:
35
+ existing = getattr(log_widget, "renderable", "") or ""
36
+ except Exception:
37
+ existing = ""
38
+ content = f"{existing}\n{msg}" if existing else msg
39
+ log_widget.update(content)
40
+ except Exception:
41
+ pass
42
+
43
+
44
+ def collect_non_empty_lines(text: str | None) -> list[str]:
45
+ """Return non-empty trimmed lines from text."""
46
+ if not text:
47
+ return []
48
+ return [ln.strip() for ln in text.splitlines() if ln.strip()]
49
+
50
+
51
+ def first(iterable: Iterable[str]) -> str | None:
52
+ """Return first element or None."""
53
+ for item in iterable:
54
+ return item
55
+ return None
@@ -0,0 +1,31 @@
1
+ """Keymap definition for the TUI.
2
+
3
+ This module keeps a data-only representation of key bindings so that
4
+ `app.py` can transform them into Textual `Binding`s via the compat layer.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import NamedTuple
10
+
11
+
12
+ class KeyBinding(NamedTuple):
13
+ key: str
14
+ action: str
15
+ description: str
16
+ show: bool = False
17
+ key_display: str | None = None
18
+ priority: bool = False
19
+
20
+
21
+ # Default keymap for the TUI
22
+ KEYMAP: list[KeyBinding] = [
23
+ KeyBinding("q", "close_overlays", "Close panel / Quit", True, None, True),
24
+ KeyBinding("ctrl+c", "cancel", "Cancel run", True, None, True),
25
+ KeyBinding("h", "toggle_help", "Help", True, None, True),
26
+ KeyBinding("r", "confirm", "Run"),
27
+ # Priority toggles so they work during input and runs
28
+ KeyBinding("s", "toggle_summary", "Summary", True, None, True),
29
+ KeyBinding("o", "toggle_output", "Output", True, None, True),
30
+ KeyBinding("t", "toggle_theme", "Theme", True, None, True),
31
+ ]
@@ -0,0 +1,111 @@
1
+ """Layout builders for the Textual TUI.
2
+
3
+ Pure functions that compose the widget tree. Keeps UI structure separate from
4
+ behavior, enabling easier testing and maintenance.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from network_toolkit.tui.constants import (
12
+ ID_ACTIONS_TABS,
13
+ ID_BOTTOM,
14
+ ID_FILTER_DEVICES,
15
+ ID_FILTER_GROUPS,
16
+ ID_FILTER_OUTPUT,
17
+ ID_FILTER_SEQUENCES,
18
+ ID_FILTER_SUMMARY,
19
+ ID_HELP_LOG,
20
+ ID_HELP_PANEL,
21
+ ID_INPUT_COMMANDS,
22
+ ID_LAYOUT,
23
+ ID_LIST_DEVICES,
24
+ ID_LIST_GROUPS,
25
+ ID_LIST_SEQUENCES,
26
+ ID_OUTPUT_LOG,
27
+ ID_OUTPUT_PANEL,
28
+ ID_OUTPUT_TAB_ALL,
29
+ ID_OUTPUT_TABS,
30
+ ID_RUN_BUTTON,
31
+ ID_RUN_STATUS,
32
+ ID_RUN_SUMMARY,
33
+ ID_SUMMARY_PANEL,
34
+ ID_TAB_COMMANDS,
35
+ ID_TAB_DEVICES,
36
+ ID_TAB_GROUPS,
37
+ ID_TAB_SEQUENCES,
38
+ ID_TARGETS_TABS,
39
+ LBL_ACTIONS,
40
+ LBL_HELP,
41
+ LBL_OUTPUT,
42
+ LBL_PRESS_ENTER,
43
+ LBL_RUN,
44
+ LBL_SUMMARY,
45
+ LBL_TARGETS,
46
+ )
47
+
48
+
49
+ def compose_root(compat: Any) -> Any:
50
+ header = compat.Header
51
+ footer = compat.Footer
52
+ vertical = compat.Vertical
53
+ horizontal = compat.Horizontal
54
+ static = compat.Static
55
+ tab_pane = compat.TabPane
56
+ tabbed_content = compat.TabbedContent
57
+
58
+ yield header(show_clock=True)
59
+ with vertical(id=ID_LAYOUT):
60
+ with horizontal(id="top"):
61
+ with vertical(classes="panel"):
62
+ yield static(LBL_TARGETS, classes="pane-title title")
63
+ with tabbed_content(id=ID_TARGETS_TABS):
64
+ with tab_pane("Devices", id=ID_TAB_DEVICES):
65
+ yield _filter_input(
66
+ compat, ID_FILTER_DEVICES, "Filter devices..."
67
+ )
68
+ yield compat.SelectionList(id=ID_LIST_DEVICES, classes="scroll")
69
+ with tab_pane("Groups", id=ID_TAB_GROUPS):
70
+ yield _filter_input(
71
+ compat, ID_FILTER_GROUPS, "Filter groups..."
72
+ )
73
+ yield compat.SelectionList(id=ID_LIST_GROUPS, classes="scroll")
74
+ with vertical(classes="panel"):
75
+ yield static(LBL_ACTIONS, classes="pane-title title")
76
+ with tabbed_content(id=ID_ACTIONS_TABS):
77
+ with tab_pane("Sequences", id=ID_TAB_SEQUENCES):
78
+ yield _filter_input(
79
+ compat, ID_FILTER_SEQUENCES, "Filter sequences..."
80
+ )
81
+ yield compat.SelectionList(
82
+ id=ID_LIST_SEQUENCES, classes="scroll"
83
+ )
84
+ with tab_pane("Commands", id=ID_TAB_COMMANDS):
85
+ yield compat.Input(
86
+ placeholder="Enter a command and press Enter to run",
87
+ id=ID_INPUT_COMMANDS,
88
+ )
89
+ yield static(LBL_PRESS_ENTER, classes="title")
90
+ yield compat.Button(LBL_RUN, id=ID_RUN_BUTTON)
91
+ with vertical(id=ID_BOTTOM):
92
+ yield static("Status: idle", id=ID_RUN_STATUS)
93
+ # No modal dialog; cancel handled via toast
94
+ with vertical(classes="panel hidden", id=ID_SUMMARY_PANEL):
95
+ yield static(LBL_SUMMARY, classes="pane-title title")
96
+ yield compat.TextLogClass(id=ID_RUN_SUMMARY, classes="scroll")
97
+ yield _filter_input(compat, ID_FILTER_SUMMARY, "Filter summary...")
98
+ with vertical(classes="panel hidden", id=ID_HELP_PANEL):
99
+ yield static(LBL_HELP, classes="pane-title title")
100
+ yield compat.TextLogClass(id=ID_HELP_LOG, classes="scroll")
101
+ with vertical(classes="panel hidden", id=ID_OUTPUT_PANEL):
102
+ yield static(LBL_OUTPUT, classes="pane-title title")
103
+ with tabbed_content(id=ID_OUTPUT_TABS):
104
+ with tab_pane("All", id=ID_OUTPUT_TAB_ALL):
105
+ yield compat.TextLogClass(id=ID_OUTPUT_LOG, classes="scroll")
106
+ yield _filter_input(compat, ID_FILTER_OUTPUT, "Filter output...")
107
+ yield footer()
108
+
109
+
110
+ def _filter_input(compat: Any, element_id: str, placeholder: str) -> Any:
111
+ return compat.Input(placeholder=placeholder, id=element_id, classes="search")
@@ -0,0 +1,93 @@
1
+ """TUI models and types (Pydantic v2).
2
+
3
+ Defines validated data structures used by the Textual UI and services layer
4
+ without importing the UI framework at module import time.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import threading
10
+ from collections.abc import Callable, Iterable
11
+
12
+ from pydantic import BaseModel, ConfigDict, Field
13
+
14
+
15
+ class SelectionState(BaseModel):
16
+ """Current user selections and inputs.
17
+
18
+ - Sets are validated from any iterable and de-duplicated.
19
+ - ``command_text`` defaults to empty string.
20
+ """
21
+
22
+ model_config = ConfigDict(frozen=False)
23
+
24
+ devices: set[str] = Field(default_factory=set)
25
+ groups: set[str] = Field(default_factory=set)
26
+ sequences: set[str] = Field(default_factory=set)
27
+ command_text: str = ""
28
+
29
+
30
+ # Execution plan mapping device -> list of commands to run
31
+ ExecutionPlan = dict[str, list[str]]
32
+
33
+
34
+ class RunResult(BaseModel):
35
+ """Summary of an execution run."""
36
+
37
+ model_config = ConfigDict(frozen=True)
38
+
39
+ total: int
40
+ successes: int
41
+ failures: int
42
+
43
+ def human_summary(self) -> str:
44
+ return (
45
+ f"Devices completed: {self.successes} succeeded, "
46
+ f"{self.failures} failed, total: {self.total}"
47
+ )
48
+
49
+
50
+ class RunCallbacks(BaseModel):
51
+ """Callbacks used to stream execution output.
52
+
53
+ All callbacks should be fast and non-blocking. They may be invoked from a
54
+ background thread. Implementations must be thread-safe.
55
+ """
56
+
57
+ model_config = ConfigDict(arbitrary_types_allowed=True)
58
+
59
+ on_output: Callable[[str], None]
60
+ on_error: Callable[[str], None]
61
+ on_meta: Callable[[str], None]
62
+ # Optional per-device output; if provided, it will be preferred over on_output
63
+ on_device_output: Callable[[str, str], None] | None = None
64
+
65
+
66
+ def iter_commands(text: str) -> Iterable[str]:
67
+ """Yield one command per non-empty line from free-form text."""
68
+ for line in (text or "").splitlines():
69
+ stripped = line.strip()
70
+ if stripped:
71
+ yield stripped
72
+
73
+
74
+ class CancellationToken:
75
+ """Thread-safe cooperative cancellation primitive.
76
+
77
+ Intended to be shared between async and thread-executed code. Supports
78
+ non-blocking checks from threads and async tasks via ``is_set``.
79
+ """
80
+
81
+ __slots__ = ("_e",)
82
+
83
+ def __init__(self) -> None:
84
+ self._e = threading.Event()
85
+
86
+ def set(self) -> None:
87
+ self._e.set()
88
+
89
+ def is_set(self) -> bool:
90
+ return self._e.is_set()
91
+
92
+ def wait(self, timeout: float | None = None) -> bool:
93
+ return self._e.wait(timeout if timeout is not None else -1)