spongebob-cli 0.3.2__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 (54) hide show
  1. spongebob/__init__.py +1 -0
  2. spongebob/__main__.py +375 -0
  3. spongebob/analyzer/__init__.py +9 -0
  4. spongebob/analyzer/__main__.py +39 -0
  5. spongebob/analyzer/analyzer.py +234 -0
  6. spongebob/bus/__init__.py +6 -0
  7. spongebob/bus/bus.py +38 -0
  8. spongebob/diagnose/__init__.py +29 -0
  9. spongebob/diagnose/__main__.py +111 -0
  10. spongebob/diagnose/adapter.py +82 -0
  11. spongebob/diagnose/models.py +79 -0
  12. spongebob/diagnose/probes.py +129 -0
  13. spongebob/engine/__init__.py +26 -0
  14. spongebob/engine/__main__.py +25 -0
  15. spongebob/engine/models.py +161 -0
  16. spongebob/engine/simulator.py +196 -0
  17. spongebob/export/__init__.py +25 -0
  18. spongebob/export/exporter.py +354 -0
  19. spongebob/meter/__init__.py +7 -0
  20. spongebob/meter/__main__.py +50 -0
  21. spongebob/meter/meter.py +140 -0
  22. spongebob/narrator/__init__.py +25 -0
  23. spongebob/narrator/narrator.py +352 -0
  24. spongebob/plugins/__init__.py +28 -0
  25. spongebob/plugins/loader.py +308 -0
  26. spongebob/plugins/models.py +47 -0
  27. spongebob/scenarios/__init__.py +25 -0
  28. spongebob/scenarios/builtin/__init__.py +1 -0
  29. spongebob/scenarios/builtin/control-line.toml +33 -0
  30. spongebob/scenarios/builtin/crowded-wifi.toml +33 -0
  31. spongebob/scenarios/builtin/flaky-last-mile.toml +33 -0
  32. spongebob/scenarios/builtin/long-haul-orbit.toml +33 -0
  33. spongebob/scenarios/builtin/overloaded-uplink.toml +35 -0
  34. spongebob/scenarios/builtin/tunnel-burst.toml +38 -0
  35. spongebob/scenarios/loader.py +205 -0
  36. spongebob/scenarios/models.py +55 -0
  37. spongebob/scenarios/runner.py +24 -0
  38. spongebob/ui/__init__.py +23 -0
  39. spongebob/ui/__main__.py +11 -0
  40. spongebob/ui/app.py +88 -0
  41. spongebob/ui/canvas.py +147 -0
  42. spongebob/ui/diagnose_screen.py +525 -0
  43. spongebob/ui/export_modal.py +158 -0
  44. spongebob/ui/menu_screen.py +159 -0
  45. spongebob/ui/replay.py +209 -0
  46. spongebob/ui/settings_screen.py +101 -0
  47. spongebob/ui/simulate_screen.py +566 -0
  48. spongebob/ui/theme.py +364 -0
  49. spongebob/ui/visualize_screen.py +411 -0
  50. spongebob_cli-0.3.2.dist-info/METADATA +78 -0
  51. spongebob_cli-0.3.2.dist-info/RECORD +54 -0
  52. spongebob_cli-0.3.2.dist-info/WHEEL +5 -0
  53. spongebob_cli-0.3.2.dist-info/entry_points.txt +2 -0
  54. spongebob_cli-0.3.2.dist-info/top_level.txt +1 -0
spongebob/bus/bus.py ADDED
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable, Iterable
4
+ from typing import Any
5
+
6
+ from spongebob.engine.models import Event
7
+
8
+ EventCallback = Callable[[Event], Any]
9
+
10
+
11
+ class EventBus:
12
+ """Synchronous publish/subscribe event bus with isolated subscriber error handling."""
13
+
14
+ def __init__(self) -> None:
15
+ self._subscribers: list[tuple[str, EventCallback]] = []
16
+
17
+ def subscribe(self, event_type_or_wildcard: str, callback: EventCallback) -> None:
18
+ """Register a callback for a specific event type or '*' for all events."""
19
+ if not isinstance(event_type_or_wildcard, str) or not event_type_or_wildcard:
20
+ raise ValueError("event_type_or_wildcard must be a non-empty string")
21
+ if not callable(callback):
22
+ raise TypeError("callback must be callable")
23
+ self._subscribers.append((event_type_or_wildcard, callback))
24
+
25
+ def publish(self, event: Event) -> None:
26
+ """Synchronously deliver an event to matching subscribers in registration order."""
27
+ for sub_type, callback in list(self._subscribers):
28
+ if sub_type == "*" or sub_type == event.type:
29
+ try:
30
+ callback(event)
31
+ except Exception:
32
+ continue
33
+
34
+
35
+ def replay(events: Iterable[Event], bus: EventBus) -> None:
36
+ """Publish a sequence of recorded events onto an EventBus in order."""
37
+ for event in events:
38
+ bus.publish(event)
@@ -0,0 +1,29 @@
1
+ from __future__ import annotations
2
+
3
+ from .adapter import AdapterResult, samples_to_events
4
+ from .models import (
5
+ EARLY_ABORT_CONSECUTIVE_ERRORS,
6
+ ERROR_OUTCOMES,
7
+ MAX_COUNT,
8
+ MAX_TIMEOUT_MS,
9
+ MIN_INTERVAL_MS,
10
+ MIN_TIMEOUT_MS,
11
+ Outcome,
12
+ Sample,
13
+ )
14
+ from .probes import probe_dns, probe_tcp
15
+
16
+ __all__ = [
17
+ "AdapterResult",
18
+ "EARLY_ABORT_CONSECUTIVE_ERRORS",
19
+ "ERROR_OUTCOMES",
20
+ "MAX_COUNT",
21
+ "MAX_TIMEOUT_MS",
22
+ "MIN_INTERVAL_MS",
23
+ "MIN_TIMEOUT_MS",
24
+ "Outcome",
25
+ "Sample",
26
+ "probe_dns",
27
+ "probe_tcp",
28
+ "samples_to_events",
29
+ ]
@@ -0,0 +1,111 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import asyncio
5
+ import sys
6
+ from collections.abc import Sequence
7
+
8
+ from .models import (
9
+ EARLY_ABORT_CONSECUTIVE_ERRORS,
10
+ ERROR_OUTCOMES,
11
+ Sample,
12
+ validate_port,
13
+ validate_probe_params,
14
+ validate_target,
15
+ )
16
+ from .probes import probe_tcp
17
+
18
+
19
+ def _build_parser() -> argparse.ArgumentParser:
20
+ parser = argparse.ArgumentParser(
21
+ prog="python -m spongebob.diagnose",
22
+ description="Run bounded TCP connect probes against a single user-specified target.",
23
+ )
24
+ parser.add_argument("host", help="Single target hostname or IP address")
25
+ parser.add_argument("--port", type=int, default=443, help="Single TCP port (1-65535)")
26
+ parser.add_argument("--count", type=int, default=20, help="Probe count (1-200)")
27
+ parser.add_argument(
28
+ "--interval-ms",
29
+ type=float,
30
+ default=200.0,
31
+ help="Interval between probes in ms (min 100)",
32
+ )
33
+ parser.add_argument(
34
+ "--timeout-ms",
35
+ type=float,
36
+ default=1000.0,
37
+ help="Per-probe connect timeout in ms (100-5000)",
38
+ )
39
+ return parser
40
+
41
+
42
+ def format_summary(samples: list[Sample], requested_count: int) -> str:
43
+ """Format raw probe counts and RTT min/avg/max summary."""
44
+ ok_count = sum(1 for s in samples if s.outcome == "ok")
45
+ timeout_count = sum(1 for s in samples if s.outcome == "timeout")
46
+ error_count = sum(1 for s in samples if s.outcome in ERROR_OUTCOMES)
47
+ rtts = [s.rtt_ms for s in samples if s.rtt_ms is not None]
48
+
49
+ lines: list[str] = []
50
+ if (
51
+ len(samples) < requested_count
52
+ and len(samples) >= EARLY_ABORT_CONSECUTIVE_ERRORS
53
+ and all(s.outcome in ERROR_OUTCOMES for s in samples[-EARLY_ABORT_CONSECUTIVE_ERRORS:])
54
+ ):
55
+ lines.append(
56
+ f"Aborted early after {EARLY_ABORT_CONSECUTIVE_ERRORS} consecutive errors "
57
+ f"(last: {samples[-1].outcome})."
58
+ )
59
+
60
+ lines.append(f"ok={ok_count} timeout={timeout_count} errors={error_count}")
61
+ if rtts:
62
+ lines.append(
63
+ f"rtt_ms: min={min(rtts):.2f} avg={sum(rtts) / len(rtts):.2f} max={max(rtts):.2f}"
64
+ )
65
+ else:
66
+ lines.append("rtt_ms: none")
67
+ lines.append(
68
+ "Note: RTT is round-trip time; TCP connect timeouts approximate packet loss and are not exact loss."
69
+ )
70
+ return "\n".join(lines)
71
+
72
+
73
+ def main(argv: Sequence[str] | None = None) -> int:
74
+ parser = _build_parser()
75
+ args = parser.parse_args(list(argv) if argv is not None else None)
76
+
77
+ try:
78
+ host = validate_target(args.host, "host")
79
+ port = validate_port(args.port)
80
+ count, interval_ms, timeout_ms = validate_probe_params(
81
+ args.count, args.interval_ms, args.timeout_ms
82
+ )
83
+ except (TypeError, ValueError) as exc:
84
+ print(f"Invalid arguments: {exc}", file=sys.stderr)
85
+ return 2
86
+
87
+ try:
88
+ answer = input(f"This will contact {host}:{port} {count} times. Continue? [y/N] ")
89
+ except (EOFError, KeyboardInterrupt):
90
+ print("\nAborted.")
91
+ return 0
92
+
93
+ if answer.strip().lower() != "y":
94
+ print("Aborted.")
95
+ return 0
96
+
97
+ samples = asyncio.run(
98
+ probe_tcp(
99
+ host=host,
100
+ port=port,
101
+ count=count,
102
+ interval_ms=interval_ms,
103
+ timeout_ms=timeout_ms,
104
+ )
105
+ )
106
+ print(format_summary(samples, count))
107
+ return 0
108
+
109
+
110
+ if __name__ == "__main__":
111
+ raise SystemExit(main())
@@ -0,0 +1,82 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping, Sequence
4
+ from dataclasses import dataclass
5
+ from typing import Literal
6
+
7
+ from spongebob.engine.models import Event, Hop
8
+
9
+ from .models import ERROR_OUTCOMES, Sample
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class AdapterResult:
14
+ """Adapted probe results ready for the meter, analyzer, and narrator pipeline."""
15
+
16
+ events: list[Event]
17
+ path: list[Hop]
18
+ latency_kind: Literal["rtt"] = "rtt"
19
+ errors: dict[str, list[Sample]] | None = None
20
+ size_bytes: int = 0
21
+
22
+
23
+ def samples_to_events(results: Mapping[str, Sequence[Sample]]) -> AdapterResult:
24
+ """Convert per-segment probe Samples into engine Events, a Hop path, and non-loss errors."""
25
+ path: list[Hop] = [Hop(name="you")]
26
+ errors: dict[str, list[Sample]] = {}
27
+ probe_items: list[tuple[float, int, int, str, Sample]] = []
28
+
29
+ for seg_idx, (segment_name, samples) in enumerate(results.items()):
30
+ path.append(Hop(name=segment_name))
31
+ for sample in samples:
32
+ if sample.outcome in ERROR_OUTCOMES:
33
+ errors.setdefault(segment_name, []).append(sample)
34
+ else:
35
+ probe_items.append(
36
+ (sample.sent_at_ms, seg_idx, sample.seq, segment_name, sample)
37
+ )
38
+
39
+ probe_items.sort(key=lambda item: (item[0], item[1], item[2]))
40
+
41
+ events: list[Event] = []
42
+ for seq, (_sent_at, _seg_idx, _orig_seq, segment_name, sample) in enumerate(probe_items):
43
+ events.append(
44
+ Event(
45
+ type="packet_sent",
46
+ seq=seq,
47
+ time_ms=sample.sent_at_ms,
48
+ hop="you",
49
+ )
50
+ )
51
+ if sample.outcome == "ok":
52
+ rtt = sample.rtt_ms if sample.rtt_ms is not None else 0.0
53
+ events.append(
54
+ Event(
55
+ type="packet_delivered",
56
+ seq=seq,
57
+ time_ms=sample.sent_at_ms + rtt,
58
+ hop=segment_name,
59
+ delay_ms=rtt,
60
+ total_latency_ms=rtt,
61
+ )
62
+ )
63
+ elif sample.outcome == "timeout":
64
+ events.append(
65
+ Event(
66
+ type="packet_dropped",
67
+ seq=seq,
68
+ time_ms=sample.sent_at_ms,
69
+ hop=segment_name,
70
+ reason="timeout",
71
+ )
72
+ )
73
+
74
+ events.sort(key=lambda e: (e.time_ms, 0 if e.type == "packet_sent" else 1, e.seq))
75
+
76
+ return AdapterResult(
77
+ events=events,
78
+ path=path,
79
+ latency_kind="rtt",
80
+ errors=errors,
81
+ size_bytes=0,
82
+ )
@@ -0,0 +1,79 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from dataclasses import dataclass
5
+ from typing import Literal
6
+
7
+ Outcome = Literal["ok", "timeout", "refused", "unreachable", "dns_error"]
8
+
9
+ ERROR_OUTCOMES: frozenset[Outcome] = frozenset({"refused", "unreachable", "dns_error"})
10
+
11
+ MAX_COUNT = 200
12
+ MIN_INTERVAL_MS = 100.0
13
+ MIN_TIMEOUT_MS = 100.0
14
+ MAX_TIMEOUT_MS = 5000.0
15
+ EARLY_ABORT_CONSECUTIVE_ERRORS = 3
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Sample:
20
+ """Single probe result with monotonic send timestamp, round-trip time, and outcome."""
21
+
22
+ seq: int
23
+ sent_at_ms: float
24
+ rtt_ms: float | None
25
+ outcome: Outcome
26
+
27
+
28
+ def validate_target(target: str, field_name: str = "host") -> str:
29
+ """Validate that a target is a single non-empty host or hostname string."""
30
+ if not isinstance(target, str):
31
+ raise TypeError(f"{field_name} must be a string, got {type(target).__name__}")
32
+ cleaned = target.strip()
33
+ if not cleaned:
34
+ raise ValueError(f"{field_name} must be a non-empty string")
35
+ if any(ch.isspace() or ch == "," for ch in cleaned):
36
+ raise ValueError(f"{field_name} must be a single target without spaces or commas")
37
+ return cleaned
38
+
39
+
40
+ def validate_port(port: int) -> int:
41
+ """Validate that port is a single integer in 1..65535."""
42
+ if isinstance(port, bool) or not isinstance(port, int):
43
+ raise TypeError(f"port must be a single integer, got {type(port).__name__}")
44
+ if port < 1 or port > 65535:
45
+ raise ValueError(f"port must be between 1 and 65535, got {port}")
46
+ return port
47
+
48
+
49
+ def _validate_finite_number(value: float, field_name: str) -> float:
50
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
51
+ raise TypeError(f"{field_name} must be a number, got {type(value).__name__}")
52
+ result = float(value)
53
+ if not math.isfinite(result):
54
+ raise ValueError(f"{field_name} must be finite, got {value}")
55
+ return result
56
+
57
+
58
+ def validate_probe_params(
59
+ count: int,
60
+ interval_ms: float,
61
+ timeout_ms: float,
62
+ ) -> tuple[int, float, float]:
63
+ """Enforce safety limits for probe count, interval, and timeout."""
64
+ if isinstance(count, bool) or not isinstance(count, int):
65
+ raise TypeError(f"count must be an integer, got {type(count).__name__}")
66
+ if count < 1 or count > MAX_COUNT:
67
+ raise ValueError(f"count must be between 1 and {MAX_COUNT}, got {count}")
68
+
69
+ interval = _validate_finite_number(interval_ms, "interval_ms")
70
+ if interval < MIN_INTERVAL_MS:
71
+ raise ValueError(f"interval_ms must be >= {MIN_INTERVAL_MS}, got {interval_ms}")
72
+
73
+ timeout = _validate_finite_number(timeout_ms, "timeout_ms")
74
+ if timeout < MIN_TIMEOUT_MS or timeout > MAX_TIMEOUT_MS:
75
+ raise ValueError(
76
+ f"timeout_ms must be between {MIN_TIMEOUT_MS} and {MAX_TIMEOUT_MS}, got {timeout_ms}"
77
+ )
78
+
79
+ return count, interval, timeout
@@ -0,0 +1,129 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import socket
5
+ import time
6
+ from collections.abc import Awaitable, Callable
7
+
8
+ from .models import (
9
+ EARLY_ABORT_CONSECUTIVE_ERRORS,
10
+ ERROR_OUTCOMES,
11
+ Outcome,
12
+ Sample,
13
+ validate_port,
14
+ validate_probe_params,
15
+ validate_target,
16
+ )
17
+
18
+
19
+ async def _run_probe_loop(
20
+ count: int,
21
+ interval_ms: float,
22
+ probe_once: Callable[[], Awaitable[tuple[Outcome, float | None]]],
23
+ ) -> list[Sample]:
24
+ """Execute a bounded probe sequence with monotonic timestamps and early error abort."""
25
+ samples: list[Sample] = []
26
+ consecutive_errors = 0
27
+
28
+ for seq in range(count):
29
+ start_s = time.monotonic()
30
+ sent_at_ms = start_s * 1000.0
31
+ outcome, rtt_ms = await probe_once()
32
+ samples.append(
33
+ Sample(
34
+ seq=seq,
35
+ sent_at_ms=sent_at_ms,
36
+ rtt_ms=rtt_ms,
37
+ outcome=outcome,
38
+ )
39
+ )
40
+
41
+ if outcome in ERROR_OUTCOMES:
42
+ consecutive_errors += 1
43
+ if consecutive_errors >= EARLY_ABORT_CONSECUTIVE_ERRORS:
44
+ break
45
+ else:
46
+ # Timeouts approximate packet loss, not errors, so they reset the error streak.
47
+ consecutive_errors = 0
48
+
49
+ if seq + 1 < count:
50
+ elapsed_ms = (time.monotonic() - start_s) * 1000.0
51
+ remaining_s = (interval_ms - elapsed_ms) / 1000.0
52
+ if remaining_s > 0.0:
53
+ await asyncio.sleep(remaining_s)
54
+
55
+ return samples
56
+
57
+
58
+ async def probe_tcp(
59
+ host: str,
60
+ port: int = 443,
61
+ count: int = 20,
62
+ interval_ms: float = 200,
63
+ timeout_ms: float = 1000,
64
+ ) -> list[Sample]:
65
+ """Time TCP connect round-trips to a single host:port without sending application data."""
66
+ target = validate_target(host, "host")
67
+ valid_port = validate_port(port)
68
+ valid_count, valid_interval, valid_timeout = validate_probe_params(
69
+ count, interval_ms, timeout_ms
70
+ )
71
+ timeout_s = valid_timeout / 1000.0
72
+
73
+ async def _once() -> tuple[Outcome, float | None]:
74
+ t0 = time.monotonic()
75
+ try:
76
+ _reader, writer = await asyncio.wait_for(
77
+ asyncio.open_connection(target, valid_port),
78
+ timeout=timeout_s,
79
+ )
80
+ rtt_ms = (time.monotonic() - t0) * 1000.0
81
+ writer.close()
82
+ try:
83
+ await writer.wait_closed()
84
+ except Exception:
85
+ pass
86
+ return "ok", rtt_ms
87
+ except (TimeoutError, asyncio.TimeoutError):
88
+ return "timeout", None
89
+ except ConnectionRefusedError:
90
+ return "refused", None
91
+ except socket.gaierror:
92
+ return "dns_error", None
93
+ except OSError:
94
+ return "unreachable", None
95
+
96
+ return await _run_probe_loop(valid_count, valid_interval, _once)
97
+
98
+
99
+ async def probe_dns(
100
+ name: str,
101
+ count: int = 20,
102
+ interval_ms: float = 200,
103
+ timeout_ms: float = 1000,
104
+ ) -> list[Sample]:
105
+ """Time system-resolver DNS lookups for a single target name."""
106
+ target = validate_target(name, "name")
107
+ valid_count, valid_interval, valid_timeout = validate_probe_params(
108
+ count, interval_ms, timeout_ms
109
+ )
110
+ timeout_s = valid_timeout / 1000.0
111
+ loop = asyncio.get_running_loop()
112
+
113
+ async def _once() -> tuple[Outcome, float | None]:
114
+ t0 = time.monotonic()
115
+ try:
116
+ await asyncio.wait_for(
117
+ loop.getaddrinfo(target, None),
118
+ timeout=timeout_s,
119
+ )
120
+ rtt_ms = (time.monotonic() - t0) * 1000.0
121
+ return "ok", rtt_ms
122
+ except (TimeoutError, asyncio.TimeoutError):
123
+ return "timeout", None
124
+ except socket.gaierror:
125
+ return "dns_error", None
126
+ except OSError:
127
+ return "unreachable", None
128
+
129
+ return await _run_probe_loop(valid_count, valid_interval, _once)
@@ -0,0 +1,26 @@
1
+ from .models import (
2
+ DropReason,
3
+ Event,
4
+ EventType,
5
+ Flow,
6
+ Hop,
7
+ JitterModel,
8
+ LossModel,
9
+ Packet,
10
+ default_path,
11
+ )
12
+ from .simulator import Simulator, simulate
13
+
14
+ __all__ = [
15
+ "DropReason",
16
+ "Event",
17
+ "EventType",
18
+ "Flow",
19
+ "Hop",
20
+ "JitterModel",
21
+ "LossModel",
22
+ "Packet",
23
+ "Simulator",
24
+ "default_path",
25
+ "simulate",
26
+ ]
@@ -0,0 +1,25 @@
1
+ from __future__ import annotations
2
+
3
+ from .models import Flow, Hop
4
+ from .simulator import simulate
5
+
6
+
7
+ def main() -> None:
8
+ path = [
9
+ Hop(name="client", delay_ms=5.0, jitter_ms=1.0, loss_pct=0.0),
10
+ Hop(name="router", delay_ms=15.0, jitter_ms=5.0, loss_pct=2.0),
11
+ Hop(name="isp", delay_ms=25.0, jitter_ms=8.0, loss_pct=3.0),
12
+ Hop(name="server", delay_ms=5.0, jitter_ms=1.0, loss_pct=0.0),
13
+ ]
14
+ flow = Flow(packet_count=100, interval_ms=10.0, size_bytes=64)
15
+ events = simulate(flow=flow, path=path, seed=42)
16
+
17
+ sent = sum(1 for event in events if event.type == "packet_sent")
18
+ delivered = sum(1 for event in events if event.type == "packet_delivered")
19
+ dropped = sum(1 for event in events if event.type == "packet_dropped")
20
+
21
+ print(f"sent={sent} delivered={delivered} dropped={dropped}")
22
+
23
+
24
+ if __name__ == "__main__":
25
+ main()
@@ -0,0 +1,161 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from dataclasses import dataclass
5
+ from typing import Literal
6
+
7
+ JitterModel = Literal["uniform", "normal"]
8
+ LossModel = Literal["random", "gilbert"]
9
+ DropReason = Literal["random", "burst", "queue_full", "timeout"]
10
+ EventType = Literal[
11
+ "packet_sent",
12
+ "packet_delayed",
13
+ "packet_dropped",
14
+ "packet_delivered",
15
+ ]
16
+
17
+ DEFAULT_HOP_NAMES: tuple[str, ...] = ("client", "router", "isp", "server")
18
+
19
+
20
+ def _validate_non_negative_finite(value: float, field_name: str) -> float:
21
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
22
+ raise TypeError(f"{field_name} must be a number, got {type(value).__name__}")
23
+ result = float(value)
24
+ if not math.isfinite(result) or result < 0.0:
25
+ raise ValueError(f"{field_name} must be a finite non-negative number, got {value}")
26
+ return result
27
+
28
+
29
+ def _validate_positive_int(value: int, field_name: str) -> int:
30
+ if isinstance(value, bool) or not isinstance(value, int):
31
+ raise TypeError(f"{field_name} must be an integer, got {type(value).__name__}")
32
+ if value <= 0:
33
+ raise ValueError(f"{field_name} must be a positive integer, got {value}")
34
+ return value
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Hop:
39
+ """A single network hop with independent delay, jitter, loss, and bandwidth settings."""
40
+
41
+ name: str
42
+ delay_ms: float = 0.0
43
+ jitter_ms: float = 0.0
44
+ loss_pct: float = 0.0
45
+ jitter_model: JitterModel = "uniform"
46
+ bandwidth_kbps: float | None = None
47
+ queue_limit_packets: int | None = None
48
+ loss_model: LossModel = "random"
49
+ p_good_to_bad: float = 0.0
50
+ p_bad_to_good: float = 0.0
51
+ loss_good: float = 0.0
52
+ loss_bad: float = 100.0
53
+
54
+ def __post_init__(self) -> None:
55
+ if not isinstance(self.name, str) or not self.name.strip():
56
+ raise ValueError("hop name must be a non-empty string")
57
+ object.__setattr__(
58
+ self, "delay_ms", _validate_non_negative_finite(self.delay_ms, "delay_ms")
59
+ )
60
+ object.__setattr__(
61
+ self, "jitter_ms", _validate_non_negative_finite(self.jitter_ms, "jitter_ms")
62
+ )
63
+ loss = _validate_non_negative_finite(self.loss_pct, "loss_pct")
64
+ if loss > 100.0:
65
+ raise ValueError(f"loss_pct must be between 0 and 100, got {self.loss_pct}")
66
+ object.__setattr__(self, "loss_pct", loss)
67
+ if self.jitter_model not in ("uniform", "normal"):
68
+ raise ValueError(
69
+ f"jitter_model must be 'uniform' or 'normal', got {self.jitter_model!r}"
70
+ )
71
+ if self.bandwidth_kbps is not None:
72
+ bw = _validate_non_negative_finite(self.bandwidth_kbps, "bandwidth_kbps")
73
+ if bw <= 0.0:
74
+ raise ValueError(f"bandwidth_kbps must be > 0, got {self.bandwidth_kbps}")
75
+ object.__setattr__(self, "bandwidth_kbps", bw)
76
+ if self.queue_limit_packets is not None:
77
+ _validate_positive_int(self.queue_limit_packets, "queue_limit_packets")
78
+ if self.loss_model not in ("random", "gilbert"):
79
+ raise ValueError(
80
+ f"loss_model must be 'random' or 'gilbert', got {self.loss_model!r}"
81
+ )
82
+ for prob_field in ("p_good_to_bad", "p_bad_to_good"):
83
+ prob = _validate_non_negative_finite(getattr(self, prob_field), prob_field)
84
+ if prob > 1.0:
85
+ raise ValueError(f"{prob_field} must be between 0 and 1, got {prob}")
86
+ object.__setattr__(self, prob_field, prob)
87
+ for pct_field in ("loss_good", "loss_bad"):
88
+ pct = _validate_non_negative_finite(getattr(self, pct_field), pct_field)
89
+ if pct > 100.0:
90
+ raise ValueError(f"{pct_field} must be between 0 and 100, got {pct}")
91
+ object.__setattr__(self, pct_field, pct)
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class Flow:
96
+ """Definition of a packet stream to inject into a simulated path."""
97
+
98
+ packet_count: int
99
+ interval_ms: float = 10.0
100
+ size_bytes: int = 64
101
+
102
+ def __post_init__(self) -> None:
103
+ _validate_positive_int(self.packet_count, "packet_count")
104
+ object.__setattr__(
105
+ self,
106
+ "interval_ms",
107
+ _validate_non_negative_finite(self.interval_ms, "interval_ms"),
108
+ )
109
+ _validate_positive_int(self.size_bytes, "size_bytes")
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class Packet:
114
+ """A simulated packet carrying sequence number, size, and send timestamp."""
115
+
116
+ seq: int
117
+ size_bytes: int
118
+ send_time_ms: float
119
+
120
+ def __post_init__(self) -> None:
121
+ if isinstance(self.seq, bool) or not isinstance(self.seq, int) or self.seq < 0:
122
+ raise ValueError(f"seq must be a non-negative integer, got {self.seq}")
123
+ _validate_positive_int(self.size_bytes, "size_bytes")
124
+ object.__setattr__(
125
+ self,
126
+ "send_time_ms",
127
+ _validate_non_negative_finite(self.send_time_ms, "send_time_ms"),
128
+ )
129
+
130
+
131
+ @dataclass(frozen=True)
132
+ class Event:
133
+ """Chronological simulation event record emitted by the engine."""
134
+
135
+ type: EventType
136
+ seq: int
137
+ time_ms: float
138
+ hop: str | None
139
+ delay_ms: float | None = None
140
+ total_latency_ms: float | None = None
141
+ reason: DropReason | None = None
142
+ queue_depth: int | None = None
143
+
144
+
145
+ def default_path(
146
+ delay_ms: float = 0.0,
147
+ jitter_ms: float = 0.0,
148
+ loss_pct: float = 0.0,
149
+ jitter_model: JitterModel = "uniform",
150
+ ) -> list[Hop]:
151
+ """Return the default 4-hop path (client, router, isp, server)."""
152
+ return [
153
+ Hop(
154
+ name=name,
155
+ delay_ms=delay_ms,
156
+ jitter_ms=jitter_ms,
157
+ loss_pct=loss_pct,
158
+ jitter_model=jitter_model,
159
+ )
160
+ for name in DEFAULT_HOP_NAMES
161
+ ]