apipulse 0.1.1__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.
apipulse/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """apipulse: a health tracker for the APIs your application depends on."""
2
+
3
+ __version__ = "0.1.1"
apipulse/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
apipulse/cli.py ADDED
@@ -0,0 +1,168 @@
1
+ """apipulse CLI: watch an API, keep its history, report and diagnose.
2
+
3
+ apipulse watch <url> [--count N] [--interval S] [--max-latency-ms MS] [-H 'Name: value']
4
+ apipulse report <url>
5
+ apipulse diagnose <url>
6
+ """
7
+
8
+ import argparse
9
+ import sys
10
+ import time
11
+ from contextlib import closing
12
+ from typing import Mapping
13
+ from urllib.parse import urlsplit
14
+
15
+ from .diagnose import diagnose, worst_severity
16
+ from .monitor import CLIENT_ERROR_STATUS, percentile
17
+ from .probe import probe, validate_headers
18
+ from .store import DEFAULT_DB_PATH, ProbeRecord, load_recent, open_db, save
19
+
20
+ DEFAULT_COUNT = 10
21
+ DEFAULT_INTERVAL_SECONDS = 1.0
22
+ DEFAULT_HISTORY_LIMIT = 50
23
+
24
+ EXIT_OK = 0
25
+ EXIT_WARNING = 1
26
+ EXIT_CRITICAL = 2
27
+ EXIT_BAD_INPUT = 3
28
+ SEVERITY_EXIT = {"info": EXIT_OK, "warning": EXIT_WARNING, "critical": EXIT_CRITICAL}
29
+
30
+
31
+ def _is_http_url(url: str) -> bool:
32
+ parts = urlsplit(url)
33
+ return parts.scheme in ("http", "https") and bool(parts.hostname)
34
+
35
+
36
+ def _probe_record(url: str, headers: Mapping[str, str]) -> ProbeRecord:
37
+ now = time.time()
38
+ try:
39
+ return ProbeRecord.from_result(probe(url, headers=headers), now)
40
+ except (OSError, ValueError) as error: # unreachable, timeout, TLS or garbled response
41
+ return ProbeRecord.from_error(url, error, now)
42
+
43
+
44
+ def _format_record(record: ProbeRecord, max_latency_ms: float | None) -> str:
45
+ if record.error:
46
+ return f"FAIL {record.error}"
47
+ flags = []
48
+ if record.is_failure:
49
+ flags.append("server error")
50
+ elif record.status_code >= CLIENT_ERROR_STATUS:
51
+ flags.append("client error: check the URL or auth")
52
+ if max_latency_ms is not None and record.total_ms > max_latency_ms:
53
+ flags.append(f"slower than {max_latency_ms:g} ms")
54
+ tag = "ALERT " if flags else "ok "
55
+ line = (
56
+ f"{tag} {record.status_code} total={record.total_ms:.1f} ms "
57
+ f"ttfb={record.ttfb_ms:.1f} ms"
58
+ )
59
+ return f"{line} [{', '.join(flags)}]" if flags else line
60
+
61
+
62
+ def cmd_watch(args: argparse.Namespace) -> int:
63
+ headers = dict(args.header)
64
+ try:
65
+ validate_headers(headers)
66
+ except ValueError as error:
67
+ print(f"bad header: {error}", file=sys.stderr)
68
+ return EXIT_BAD_INPUT
69
+
70
+ saw_problem = False
71
+ with closing(open_db(args.db)) as connection:
72
+ try:
73
+ for attempt in range(args.count):
74
+ if attempt > 0:
75
+ time.sleep(args.interval)
76
+ record = _probe_record(args.url, headers)
77
+ save(connection, record)
78
+ saw_problem = saw_problem or record.is_failure
79
+ print(_format_record(record, args.max_latency_ms))
80
+ except KeyboardInterrupt:
81
+ print("stopped")
82
+ return EXIT_WARNING if saw_problem else EXIT_OK
83
+
84
+
85
+ def cmd_report(args: argparse.Namespace) -> int:
86
+ with closing(open_db(args.db)) as connection:
87
+ records = load_recent(connection, args.url, args.limit)
88
+ if not records:
89
+ print(f"no history for {args.url}")
90
+ return EXIT_OK
91
+
92
+ latencies = sorted(r.total_ms for r in records if r.total_ms is not None)
93
+ failed = sum(1 for r in records if r.is_failure)
94
+ print(f"{args.url}: last {len(records)} probes, {failed} failed")
95
+ if latencies:
96
+ print(f" min {latencies[0]:.2f} ms")
97
+ print(f" p50 {percentile(latencies, 0.50):.2f} ms")
98
+ print(f" p95 {percentile(latencies, 0.95):.2f} ms")
99
+ print(f" max {latencies[-1]:.2f} ms")
100
+ else:
101
+ print(" no successful responses")
102
+ return EXIT_OK
103
+
104
+
105
+ def cmd_diagnose(args: argparse.Namespace) -> int:
106
+ with closing(open_db(args.db)) as connection:
107
+ records = load_recent(connection, args.url, args.limit)
108
+ findings = diagnose(records)
109
+ for finding in findings:
110
+ print(f"[{finding.severity.upper()}] {finding.message}")
111
+ return SEVERITY_EXIT[worst_severity(findings)]
112
+
113
+
114
+ def _header(text: str) -> tuple[str, str]:
115
+ name, separator, value = text.partition(":")
116
+ if not separator or not name.strip():
117
+ # deliberately not echoing `text`: it may contain a token
118
+ raise argparse.ArgumentTypeError("expected 'Name: value'")
119
+ return name.strip(), value.strip()
120
+
121
+
122
+ def _positive_int(text: str) -> int:
123
+ value = int(text)
124
+ if value < 1:
125
+ raise argparse.ArgumentTypeError("must be at least 1")
126
+ return value
127
+
128
+
129
+ def build_parser() -> argparse.ArgumentParser:
130
+ parser = argparse.ArgumentParser(prog="apipulse", description="API health tracker.")
131
+ commands = parser.add_subparsers(dest="command", required=True)
132
+
133
+ def add_common(sub: argparse.ArgumentParser) -> None:
134
+ sub.add_argument("url")
135
+ sub.add_argument("--db", default=DEFAULT_DB_PATH, help="SQLite history file")
136
+
137
+ watch = commands.add_parser("watch", help="probe repeatedly and save results")
138
+ add_common(watch)
139
+ watch.add_argument("--count", type=_positive_int, default=DEFAULT_COUNT)
140
+ watch.add_argument("--interval", type=float, default=DEFAULT_INTERVAL_SECONDS)
141
+ watch.add_argument("--max-latency-ms", type=float, default=None,
142
+ help="flag probes slower than this")
143
+ watch.add_argument("-H", "--header", action="append", type=_header, default=[],
144
+ metavar="'Name: value'",
145
+ help="extra request header, repeatable (never saved to the history)")
146
+ watch.set_defaults(handler=cmd_watch)
147
+
148
+ for name, handler, help_text in (
149
+ ("report", cmd_report, "latency percentiles from history"),
150
+ ("diagnose", cmd_diagnose, "explain what looks wrong"),
151
+ ):
152
+ sub = commands.add_parser(name, help=help_text)
153
+ add_common(sub)
154
+ sub.add_argument("--limit", type=_positive_int, default=DEFAULT_HISTORY_LIMIT)
155
+ sub.set_defaults(handler=handler)
156
+ return parser
157
+
158
+
159
+ def main(argv: list[str] | None = None) -> int:
160
+ args = build_parser().parse_args(argv)
161
+ if not _is_http_url(args.url):
162
+ print(f"expected an http(s) URL, got {args.url!r}", file=sys.stderr)
163
+ return EXIT_BAD_INPUT
164
+ return args.handler(args)
165
+
166
+
167
+ if __name__ == "__main__":
168
+ sys.exit(main(sys.argv[1:]))
apipulse/diagnose.py ADDED
@@ -0,0 +1,122 @@
1
+ """apipulse diagnose: rule-based reading of probe history.
2
+
3
+ Turns raw timings into plain-language findings, such as which phase of the
4
+ request got slower. This is the layer an LLM could later explain or extend.
5
+ """
6
+
7
+ import statistics
8
+ from dataclasses import dataclass
9
+ from typing import Sequence
10
+
11
+ from .monitor import CLIENT_ERROR_STATUS, SERVER_ERROR_STATUS, percentile
12
+ from .store import ProbeRecord
13
+
14
+ MIN_RECORDS_FOR_TREND = 6
15
+ SLOWDOWN_FACTOR = 2.0 # recent median this many times the baseline median
16
+ MIN_SLOWDOWN_MS = 20.0 # ignore "doubling" of tiny numbers
17
+ SPREAD_FACTOR = 3.0 # p95 this many times p50 means inconsistent latency
18
+ MIN_SPREAD_MS = 20.0
19
+ CRITICAL_FAILURE_RATE = 0.5
20
+
21
+ PHASES = {
22
+ "dns_ms": "DNS lookup",
23
+ "connect_ms": "TCP connect (network path or a full accept queue)",
24
+ "tls_ms": "TLS handshake",
25
+ "ttfb_ms": "server processing time (the API itself is slow)",
26
+ }
27
+
28
+ SEVERITY_RANK = {"info": 0, "warning": 1, "critical": 2}
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Finding:
33
+ severity: str # "info" | "warning" | "critical"
34
+ message: str
35
+
36
+
37
+ def worst_severity(findings: Sequence[Finding]) -> str:
38
+ return max((f.severity for f in findings), key=SEVERITY_RANK.__getitem__, default="info")
39
+
40
+
41
+ def _availability(records: Sequence[ProbeRecord]) -> tuple[Finding, ...]:
42
+ failures = [r for r in records if r.is_failure]
43
+ if not failures:
44
+ return ()
45
+ rate = len(failures) / len(records)
46
+ latest_error = next((r.error for r in reversed(failures) if r.error), None)
47
+ latest_status = next((r.status_code for r in reversed(failures) if r.error is None), None)
48
+ detail = latest_error or (f"latest status {latest_status}" if latest_status else "")
49
+ severity = "critical" if rate >= CRITICAL_FAILURE_RATE else "warning"
50
+ message = f"{len(failures)} of {len(records)} probes failed ({rate:.0%})"
51
+ return (Finding(severity, f"{message}; {detail}" if detail else message),)
52
+
53
+
54
+ def _client_errors(records: Sequence[ProbeRecord]) -> tuple[Finding, ...]:
55
+ # 4xx is not an outage, but it usually means the probe itself is misconfigured
56
+ rejected = [
57
+ r for r in records
58
+ if r.status_code is not None and CLIENT_ERROR_STATUS <= r.status_code < SERVER_ERROR_STATUS
59
+ ]
60
+ if not rejected:
61
+ return ()
62
+ return (
63
+ Finding(
64
+ "warning",
65
+ f"{len(rejected)} of {len(records)} probes got a 4xx response "
66
+ f"(latest {rejected[-1].status_code}); check the URL or credentials",
67
+ ),
68
+ )
69
+
70
+
71
+ def _spread(timed: Sequence[ProbeRecord]) -> tuple[Finding, ...]:
72
+ if len(timed) < 2:
73
+ return ()
74
+ latencies = sorted(r.total_ms for r in timed)
75
+ p50, p95 = percentile(latencies, 0.50), percentile(latencies, 0.95)
76
+ if p95 > SPREAD_FACTOR * p50 and p95 - p50 > MIN_SPREAD_MS:
77
+ return (Finding("warning", f"Latency is inconsistent: p50 {p50:.0f} ms but p95 {p95:.0f} ms"),)
78
+ return ()
79
+
80
+
81
+ def _median(records: Sequence[ProbeRecord], phase: str) -> float:
82
+ return statistics.median(getattr(r, phase) for r in records)
83
+
84
+
85
+ def _slowdown(timed: Sequence[ProbeRecord]) -> tuple[Finding, ...]:
86
+ if len(timed) < MIN_RECORDS_FOR_TREND:
87
+ return ()
88
+ half = len(timed) // 2
89
+ baseline, recent = timed[:half], timed[half:]
90
+ before, after = _median(baseline, "total_ms"), _median(recent, "total_ms")
91
+ if after < SLOWDOWN_FACTOR * before or after - before < MIN_SLOWDOWN_MS:
92
+ return ()
93
+
94
+ growth = {phase: _median(recent, phase) - _median(baseline, phase) for phase in PHASES}
95
+ culprit = max(growth, key=growth.__getitem__)
96
+ return (
97
+ Finding(
98
+ "warning",
99
+ f"Slowed down: median latency rose from {before:.0f} ms to {after:.0f} ms. "
100
+ f"Biggest increase: {PHASES[culprit]} (+{growth[culprit]:.0f} ms)",
101
+ ),
102
+ )
103
+
104
+
105
+ def diagnose(records: Sequence[ProbeRecord]) -> tuple[Finding, ...]:
106
+ """Findings for records ordered oldest first; a single 'info' finding means healthy."""
107
+ if not records:
108
+ return (Finding("info", "No data yet: run `watch` first"),)
109
+
110
+ timed = [r for r in records if r.error is None and r.total_ms is not None]
111
+ findings = _availability(records) + _client_errors(records) + _spread(timed) + _slowdown(timed)
112
+ if findings:
113
+ return findings
114
+
115
+ latencies = sorted(r.total_ms for r in timed)
116
+ return (
117
+ Finding(
118
+ "info",
119
+ f"Healthy: p50 {percentile(latencies, 0.50):.1f} ms, "
120
+ f"p95 {percentile(latencies, 0.95):.1f} ms over {len(timed)} probes",
121
+ ),
122
+ )
apipulse/monitor.py ADDED
@@ -0,0 +1,102 @@
1
+ """apipulse monitor: probe a URL repeatedly and report latency percentiles."""
2
+
3
+ import argparse
4
+ import math
5
+ import sys
6
+ import time
7
+ from dataclasses import dataclass
8
+ from typing import Callable, Sequence
9
+
10
+ from .probe import ProbeResult, probe
11
+
12
+ DEFAULT_COUNT = 10
13
+ DEFAULT_INTERVAL_SECONDS = 1.0
14
+ SERVER_ERROR_STATUS = 500
15
+ CLIENT_ERROR_STATUS = 400
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Summary:
20
+ url: str
21
+ attempts: int
22
+ failed: int # connection errors plus 5xx responses
23
+ min_ms: float | None
24
+ p50_ms: float | None
25
+ p95_ms: float | None
26
+ max_ms: float | None
27
+
28
+
29
+ def percentile(sorted_values: Sequence[float], fraction: float) -> float:
30
+ """Nearest-rank percentile of an ascending, non-empty sequence."""
31
+ if not sorted_values:
32
+ raise ValueError("percentile of an empty sequence")
33
+ rank = max(1, math.ceil(fraction * len(sorted_values)))
34
+ return sorted_values[rank - 1]
35
+
36
+
37
+ def summarize(url: str, attempts: int, results: Sequence[ProbeResult]) -> Summary:
38
+ """Summarize attempts; `results` holds only the probes that got a response."""
39
+ server_errors = sum(1 for r in results if r.status_code >= SERVER_ERROR_STATUS)
40
+ failed = (attempts - len(results)) + server_errors
41
+ latencies = sorted(r.total_ms for r in results)
42
+ if not latencies:
43
+ return Summary(url, attempts, failed, None, None, None, None)
44
+ return Summary(
45
+ url=url,
46
+ attempts=attempts,
47
+ failed=failed,
48
+ min_ms=latencies[0],
49
+ p50_ms=percentile(latencies, 0.50),
50
+ p95_ms=percentile(latencies, 0.95),
51
+ max_ms=latencies[-1],
52
+ )
53
+
54
+
55
+ def run_monitor(
56
+ url: str,
57
+ count: int = DEFAULT_COUNT,
58
+ interval: float = DEFAULT_INTERVAL_SECONDS,
59
+ probe_fn: Callable[[str], ProbeResult] = probe,
60
+ sleep: Callable[[float], None] = time.sleep,
61
+ ) -> Summary:
62
+ if count < 1:
63
+ raise ValueError("count must be at least 1")
64
+
65
+ results: list[ProbeResult] = []
66
+ for attempt in range(count):
67
+ if attempt > 0:
68
+ sleep(interval)
69
+ try:
70
+ results.append(probe_fn(url))
71
+ except OSError:
72
+ continue # unreachable this round; counted as failed in summarize
73
+ return summarize(url, count, results)
74
+
75
+
76
+ def _format_ms(value: float | None) -> str:
77
+ return "n/a" if value is None else f"{value:.2f} ms"
78
+
79
+
80
+ def main(argv: list[str]) -> int:
81
+ parser = argparse.ArgumentParser(description="Probe a URL repeatedly.")
82
+ parser.add_argument("url")
83
+ parser.add_argument("--count", type=int, default=DEFAULT_COUNT)
84
+ parser.add_argument("--interval", type=float, default=DEFAULT_INTERVAL_SECONDS)
85
+ args = parser.parse_args(argv[1:])
86
+
87
+ try:
88
+ summary = run_monitor(args.url, args.count, args.interval)
89
+ except ValueError as error:
90
+ print(f"monitor failed: {error}", file=sys.stderr)
91
+ return 1
92
+
93
+ print(f"{summary.url}: {summary.attempts} probes, {summary.failed} failed")
94
+ print(f" min {_format_ms(summary.min_ms)}")
95
+ print(f" p50 {_format_ms(summary.p50_ms)}")
96
+ print(f" p95 {_format_ms(summary.p95_ms)}")
97
+ print(f" max {_format_ms(summary.max_ms)}")
98
+ return 0 if summary.failed == 0 else 1
99
+
100
+
101
+ if __name__ == "__main__":
102
+ sys.exit(main(sys.argv))
apipulse/probe.py ADDED
@@ -0,0 +1,166 @@
1
+ """apipulse probe: one HTTP request over a raw socket, timed phase by phase."""
2
+
3
+ import socket
4
+ import ssl
5
+ import sys
6
+ import time
7
+ from dataclasses import dataclass
8
+ from typing import Mapping, Sequence
9
+ from urllib.parse import urlsplit
10
+
11
+ TIMEOUT_SECONDS = 10.0
12
+ RECV_CHUNK_BYTES = 4096
13
+ HTTP_PORT = 80
14
+ HTTPS_PORT = 443
15
+ DEFAULT_USER_AGENT = "apipulse/0.1"
16
+ # We set these ourselves: Connection: close is what lets us read the body until EOF.
17
+ RESERVED_HEADERS = frozenset({"host", "connection"})
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class ProbeResult:
22
+ url: str
23
+ status_code: int
24
+ dns_ms: float
25
+ connect_ms: float
26
+ tls_ms: float
27
+ ttfb_ms: float # time to first byte, measured from the moment the request is sent
28
+ total_ms: float
29
+ body_bytes: int
30
+
31
+
32
+ def _ms(start: float, end: float) -> float:
33
+ return round((end - start) * 1000, 2)
34
+
35
+
36
+ def _parse_status(first_chunk: bytes) -> int:
37
+ # Status line looks like: b"HTTP/1.1 200 OK\r\n..."
38
+ status_line = first_chunk.split(b"\r\n", 1)[0].decode("ascii", errors="replace")
39
+ parts = status_line.split(" ", 2)
40
+ if len(parts) < 2 or not parts[1].isdigit():
41
+ raise ValueError(f"malformed status line: {status_line!r}")
42
+ return int(parts[1])
43
+
44
+
45
+ def validate_headers(headers: Mapping[str, str]) -> None:
46
+ """Raise ValueError for headers that could corrupt the request.
47
+
48
+ Messages never include header values, which may be secrets such as tokens.
49
+ """
50
+ for name, value in headers.items():
51
+ if not name or any(ch in name for ch in ":\r\n \t"):
52
+ raise ValueError(f"invalid header name: {name!r}")
53
+ if "\r" in value or "\n" in value:
54
+ raise ValueError(f"invalid value for header {name!r}: line breaks are not allowed")
55
+ if name.lower() in RESERVED_HEADERS:
56
+ raise ValueError(f"header {name!r} is set by apipulse and cannot be overridden")
57
+
58
+
59
+ def _build_request(netloc: str, path: str, headers: Mapping[str, str]) -> bytes:
60
+ validate_headers(headers)
61
+ # lower-cased name -> (name, value); a caller's header replaces our default of the same name
62
+ merged = {"user-agent": ("User-Agent", DEFAULT_USER_AGENT)}
63
+ merged.update({name.lower(): (name, value) for name, value in headers.items()})
64
+ lines = [
65
+ f"GET {path} HTTP/1.1",
66
+ f"Host: {netloc}",
67
+ *(f"{name}: {value}" for name, value in merged.values()),
68
+ "Connection: close",
69
+ ]
70
+ return ("\r\n".join(lines) + "\r\n\r\n").encode("ascii")
71
+
72
+
73
+ def _connect(addresses: Sequence[tuple], timeout: float) -> socket.socket:
74
+ """Try each resolved address in order, as browsers do.
75
+
76
+ `localhost` can resolve to ::1 and 127.0.0.1, and a server may listen on only one.
77
+ """
78
+ last_error: OSError | None = None
79
+ for family, socktype, proto, _, sockaddr in addresses:
80
+ sock = socket.socket(family, socktype, proto)
81
+ sock.settimeout(timeout)
82
+ try:
83
+ sock.connect(sockaddr)
84
+ return sock
85
+ except OSError as error:
86
+ sock.close()
87
+ last_error = error
88
+ raise last_error or OSError("no addresses to connect to")
89
+
90
+
91
+ def probe(url: str, timeout: float = TIMEOUT_SECONDS,
92
+ headers: Mapping[str, str] | None = None) -> ProbeResult:
93
+ parts = urlsplit(url)
94
+ if parts.scheme not in ("http", "https") or not parts.hostname:
95
+ raise ValueError(f"expected an http(s) URL, got {url!r}")
96
+
97
+ is_https = parts.scheme == "https"
98
+ port = parts.port or (HTTPS_PORT if is_https else HTTP_PORT)
99
+ path = (parts.path or "/") + (f"?{parts.query}" if parts.query else "")
100
+ request = _build_request(parts.netloc, path, headers or {})
101
+
102
+ t0 = time.perf_counter()
103
+ addresses = socket.getaddrinfo(parts.hostname, port, type=socket.SOCK_STREAM)
104
+ t_dns = time.perf_counter()
105
+
106
+ sock = _connect(addresses, timeout)
107
+ t_connect = time.perf_counter()
108
+
109
+ try:
110
+ if is_https:
111
+ context = ssl.create_default_context()
112
+ sock = context.wrap_socket(sock, server_hostname=parts.hostname)
113
+ t_tls = time.perf_counter()
114
+
115
+ sock.sendall(request)
116
+ t_sent = time.perf_counter()
117
+
118
+ first_chunk = sock.recv(RECV_CHUNK_BYTES)
119
+ t_first_byte = time.perf_counter()
120
+ if not first_chunk:
121
+ raise ConnectionError("server closed the connection without responding")
122
+
123
+ received = bytearray(first_chunk)
124
+ while chunk := sock.recv(RECV_CHUNK_BYTES):
125
+ received.extend(chunk)
126
+ t_done = time.perf_counter()
127
+ finally:
128
+ sock.close()
129
+
130
+ header_end = received.find(b"\r\n\r\n")
131
+ body_bytes = len(received) - (header_end + 4) if header_end != -1 else 0
132
+
133
+ return ProbeResult(
134
+ url=url,
135
+ status_code=_parse_status(first_chunk),
136
+ dns_ms=_ms(t0, t_dns),
137
+ connect_ms=_ms(t_dns, t_connect),
138
+ tls_ms=_ms(t_connect, t_tls),
139
+ ttfb_ms=_ms(t_sent, t_first_byte),
140
+ total_ms=_ms(t0, t_done),
141
+ body_bytes=body_bytes,
142
+ )
143
+
144
+
145
+ def main(argv: list[str]) -> int:
146
+ if len(argv) != 2:
147
+ print("usage: python3 probe.py <url>", file=sys.stderr)
148
+ return 2
149
+ try:
150
+ result = probe(argv[1])
151
+ except (OSError, ValueError) as error:
152
+ print(f"probe failed: {error}", file=sys.stderr)
153
+ return 1
154
+
155
+ print(f"{result.url} -> {result.status_code}")
156
+ print(f" DNS {result.dns_ms:>8} ms")
157
+ print(f" Connect {result.connect_ms:>8} ms")
158
+ print(f" TLS {result.tls_ms:>8} ms")
159
+ print(f" TTFB {result.ttfb_ms:>8} ms")
160
+ print(f" Total {result.total_ms:>8} ms")
161
+ print(f" Body {result.body_bytes:>8} bytes")
162
+ return 0
163
+
164
+
165
+ if __name__ == "__main__":
166
+ sys.exit(main(sys.argv))
apipulse/store.py ADDED
@@ -0,0 +1,95 @@
1
+ """apipulse store: keep probe history in SQLite."""
2
+
3
+ import sqlite3
4
+ from dataclasses import asdict, dataclass, fields
5
+ from typing import Sequence
6
+
7
+ from .monitor import SERVER_ERROR_STATUS
8
+ from .probe import ProbeResult
9
+
10
+ DEFAULT_DB_PATH = "apipulse.db"
11
+
12
+ SCHEMA = """
13
+ CREATE TABLE IF NOT EXISTS probes (
14
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
15
+ url TEXT NOT NULL,
16
+ timestamp REAL NOT NULL,
17
+ status_code INTEGER,
18
+ dns_ms REAL,
19
+ connect_ms REAL,
20
+ tls_ms REAL,
21
+ ttfb_ms REAL,
22
+ total_ms REAL,
23
+ body_bytes INTEGER,
24
+ error TEXT
25
+ );
26
+ CREATE INDEX IF NOT EXISTS idx_probes_url_time ON probes (url, timestamp);
27
+ """
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class ProbeRecord:
32
+ """One probe attempt: either a response (timings set) or an error."""
33
+
34
+ url: str
35
+ timestamp: float # epoch seconds
36
+ status_code: int | None = None
37
+ dns_ms: float | None = None
38
+ connect_ms: float | None = None
39
+ tls_ms: float | None = None
40
+ ttfb_ms: float | None = None
41
+ total_ms: float | None = None
42
+ body_bytes: int | None = None
43
+ error: str | None = None
44
+
45
+ @property
46
+ def is_failure(self) -> bool:
47
+ return self.error is not None or (self.status_code or 0) >= SERVER_ERROR_STATUS
48
+
49
+ @classmethod
50
+ def from_result(cls, result: ProbeResult, timestamp: float) -> "ProbeRecord":
51
+ return cls(
52
+ url=result.url,
53
+ timestamp=timestamp,
54
+ status_code=result.status_code,
55
+ dns_ms=result.dns_ms,
56
+ connect_ms=result.connect_ms,
57
+ tls_ms=result.tls_ms,
58
+ ttfb_ms=result.ttfb_ms,
59
+ total_ms=result.total_ms,
60
+ body_bytes=result.body_bytes,
61
+ )
62
+
63
+ @classmethod
64
+ def from_error(cls, url: str, error: Exception, timestamp: float) -> "ProbeRecord":
65
+ return cls(url=url, timestamp=timestamp, error=f"{type(error).__name__}: {error}")
66
+
67
+
68
+ _COLUMNS = tuple(f.name for f in fields(ProbeRecord))
69
+
70
+
71
+ def open_db(path: str = DEFAULT_DB_PATH) -> sqlite3.Connection:
72
+ connection = sqlite3.connect(path)
73
+ connection.row_factory = sqlite3.Row
74
+ connection.executescript(SCHEMA)
75
+ return connection
76
+
77
+
78
+ def save(connection: sqlite3.Connection, record: ProbeRecord) -> None:
79
+ # _COLUMNS comes from the dataclass, never from user input; values are bound parameters
80
+ placeholders = ", ".join(f":{name}" for name in _COLUMNS)
81
+ connection.execute(
82
+ f"INSERT INTO probes ({', '.join(_COLUMNS)}) VALUES ({placeholders})",
83
+ asdict(record),
84
+ )
85
+ connection.commit()
86
+
87
+
88
+ def load_recent(connection: sqlite3.Connection, url: str, limit: int) -> Sequence[ProbeRecord]:
89
+ """The newest `limit` records for `url`, returned oldest first."""
90
+ rows = connection.execute(
91
+ f"SELECT {', '.join(_COLUMNS)} FROM probes "
92
+ "WHERE url = ? ORDER BY timestamp DESC, id DESC LIMIT ?",
93
+ (url, limit),
94
+ ).fetchall()
95
+ return tuple(ProbeRecord(**{name: row[name] for name in _COLUMNS}) for row in reversed(rows))
@@ -0,0 +1,153 @@
1
+ Metadata-Version: 2.4
2
+ Name: apipulse
3
+ Version: 0.1.1
4
+ Summary: A health tracker for the APIs your app depends on: raw-socket probes, per-phase timings, history and diagnosis.
5
+ Author: Athina09
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Athina09/apipulse
8
+ Project-URL: Issues, https://github.com/Athina09/apipulse/issues
9
+ Keywords: api,monitoring,http,latency,troubleshooting,sockets
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: System :: Monitoring
15
+ Classifier: Topic :: Internet :: WWW/HTTP
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Dynamic: license-file
20
+
21
+ # apipulse
22
+
23
+ [![tests](https://github.com/Athina09/apipulse/actions/workflows/tests.yml/badge.svg)](https://github.com/Athina09/apipulse/actions/workflows/tests.yml)
24
+ [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
25
+
26
+ **A health tracker for the APIs your app depends on.**
27
+
28
+ apipulse probes an HTTP API over raw sockets, times every phase of the request
29
+ (DNS, TCP connect, TLS, time to first byte), keeps the history in SQLite, and tells
30
+ you in plain language what looks wrong, including *which part* of the request got slower.
31
+
32
+ - Standard library only: no dependencies to install.
33
+ - Works on any `http://` or `https://` URL, including `localhost` and IPv6.
34
+ - Built as a learning project on sockets and HTTP internals, so the code is small and readable.
35
+
36
+ ![A healthy API](docs/healthy.svg)
37
+
38
+ ## Install
39
+
40
+ Requires Python 3.10 or newer.
41
+
42
+ ```bash
43
+ pipx install git+https://github.com/Athina09/apipulse
44
+ # or: pip install git+https://github.com/Athina09/apipulse
45
+ ```
46
+
47
+ Or run it straight from a clone, with no install:
48
+
49
+ ```bash
50
+ git clone https://github.com/Athina09/apipulse
51
+ cd apipulse
52
+ python3 -m apipulse --help
53
+ ```
54
+
55
+ ## Quick start
56
+
57
+ ```bash
58
+ apipulse watch http://127.0.0.1:3000/ --count 20 --interval 1 --max-latency-ms 200
59
+ apipulse report http://127.0.0.1:3000/
60
+ apipulse diagnose http://127.0.0.1:3000/
61
+ ```
62
+
63
+ | Command | What it does |
64
+ |---|---|
65
+ | `watch <url>` | Probes repeatedly, saves every result, flags slow or failing probes as it goes. |
66
+ | `report <url>` | Prints min, p50, p95 and max latency from the saved history. |
67
+ | `diagnose <url>` | Reads the history and explains what looks wrong. |
68
+
69
+ Useful options for `watch`: `--count N`, `--interval SECONDS`, `--max-latency-ms MS`,
70
+ and `-H 'Name: value'` (repeatable). History is stored in `apipulse.db` in the current
71
+ folder; use `--db PATH` to keep one file per project.
72
+
73
+ ### Probing an API that needs a token
74
+
75
+ ```bash
76
+ apipulse watch https://api.example.com/health -H "Authorization: Bearer $API_TOKEN"
77
+ ```
78
+
79
+ Headers are sent but **never saved** to the history, and error messages never echo
80
+ their values. Pass tokens through an environment variable, as above, so they don't
81
+ end up in your shell history.
82
+
83
+ ## What `diagnose` can tell you
84
+
85
+ ![Finding what went wrong](docs/troubleshooting.svg)
86
+
87
+ | Finding | Meaning |
88
+ |---|---|
89
+ | `critical` / `warning` failures | Connection errors or 5xx responses, with the latest error. 50% or more failing is critical. |
90
+ | 4xx responses | Usually a wrong URL or missing credentials, not an outage. |
91
+ | Inconsistent latency | p95 is more than 3x the p50. |
92
+ | Slowed down | The recent median is more than 2x the older median, **and it names the phase that grew**: DNS, TCP connect, TLS, or server processing time. |
93
+
94
+ Exit codes make it scriptable: `0` ok, `1` warning, `2` critical, `3` bad input.
95
+
96
+ ```bash
97
+ apipulse diagnose http://127.0.0.1:3000/ || echo "needs attention"
98
+ ```
99
+
100
+ ## Try it without a real API
101
+
102
+ The repo includes a small C++ HTTP server (raw sockets) that misbehaves on demand.
103
+
104
+ ```bash
105
+ g++ -std=c++17 -Wall -Wextra testserver/server.cpp -o server
106
+ ./server # listens on 127.0.0.1:8080; Ctrl-C to stop
107
+ ```
108
+
109
+ | Endpoint | Behaviour |
110
+ |---|---|
111
+ | `/` | 200 |
112
+ | `/status/<code>` | Responds with that status code (100-599) |
113
+ | `/delay/<ms>` | Waits, then 200 (capped at 10 seconds) |
114
+
115
+ It handles one client at a time, so a slow request delays the next one.
116
+
117
+ ## How it works
118
+
119
+ ```
120
+ apipulse/
121
+ probe.py one GET over a raw socket, timed by phase
122
+ monitor.py percentiles and repeated probing
123
+ store.py SQLite history (frozen dataclass records)
124
+ diagnose.py rule-based findings
125
+ cli.py the `apipulse` command
126
+ testserver/ the C++ test server
127
+ tests/ unit tests
128
+ ```
129
+
130
+ A probe resolves the name, tries each address in turn (so `localhost` works whether
131
+ the server listens on IPv4 or IPv6), connects, optionally wraps the socket in TLS,
132
+ sends a hand-built `GET` request with `Connection: close`, and reads until the server
133
+ hangs up. Each step is timed with `time.perf_counter()`.
134
+
135
+ ## Limitations
136
+
137
+ - `GET` only. No redirects, and chunked response bodies are read correctly but their
138
+ `body_bytes` count includes the chunk framing.
139
+ - `diagnose` is rule-based. It cannot see a steadily slow API as a problem; use
140
+ `watch --max-latency-ms` to flag that.
141
+ - The test server handles one client at a time.
142
+
143
+ ## Development
144
+
145
+ ```bash
146
+ python3 -m unittest discover -s tests -t . -v
147
+ ```
148
+
149
+ Contributions and bug reports are welcome. Open an issue or a pull request.
150
+
151
+ ## License
152
+
153
+ [MIT](LICENSE)
@@ -0,0 +1,13 @@
1
+ apipulse/__init__.py,sha256=JyG5Muxzv4JeACBs8faDQbOIIF1LkU24788UEujOxBs,98
2
+ apipulse/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ apipulse/cli.py,sha256=MMUvMu4Ubxexdg6ZsKa66cq4IhCU8VulLBtFwqwYbxQ,6106
4
+ apipulse/diagnose.py,sha256=QeFKIlYFHiYqs-8umm-_neD16Ek6544nUBhgJCHdXWg,4565
5
+ apipulse/monitor.py,sha256=KS_AQvi90nMzZp7L7rp_btfsGKJMNLeEI24WbpmWbzo,3213
6
+ apipulse/probe.py,sha256=McCt4lN9w475F5-7bVJMa9P7NfWXi81qwbDzmEWsY1Q,5673
7
+ apipulse/store.py,sha256=dkJmaEBrVBBpCfGBi0y-6Mmi0sNPJ3d9fhxs15_4N3w,2966
8
+ apipulse-0.1.1.dist-info/licenses/LICENSE,sha256=lB2Q5amyvbmXwQe2_8WoMIjtL2oAgfZgCfce96uIJXk,1065
9
+ apipulse-0.1.1.dist-info/METADATA,sha256=jHJ_eBukxPiv13MiB02BXHkatQlas6Nr3kWdU0Z-Ics,5305
10
+ apipulse-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ apipulse-0.1.1.dist-info/entry_points.txt,sha256=RlDxQjv5hAvrJgh8FXZIEs2uLbI_kbAJsv3gRBTVuLE,47
12
+ apipulse-0.1.1.dist-info/top_level.txt,sha256=NVTYfats4e7LmNGxbrPX_B_e9IdrsWBqtP-qoxXcVt4,9
13
+ apipulse-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ apipulse = apipulse.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Athina09
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ apipulse