seqpulse 0.1.0__tar.gz

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.
seqpulse-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Nassir
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,77 @@
1
+ Metadata-Version: 2.4
2
+ Name: seqpulse
3
+ Version: 0.1.0
4
+ Summary: SeqPulse SDK for metrics endpoint instrumentation and HMAC validation
5
+ Author: Nassir
6
+ License-Expression: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Framework :: FastAPI
12
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: psutil>=5.9.0
17
+ Requires-Dist: starlette>=0.36.0
18
+ Dynamic: license-file
19
+
20
+ # seqpulse (Python SDK)
21
+
22
+ SeqPulse SDK for:
23
+
24
+ - HTTP metrics instrumentation
25
+ - metrics endpoint exposure
26
+ - optional HMAC v2 validation on inbound SeqPulse calls
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ pip install seqpulse
32
+ ```
33
+
34
+ ## FastAPI usage
35
+
36
+ ```python
37
+ from fastapi import FastAPI
38
+ from seqpulse import SeqPulse
39
+
40
+ app = FastAPI()
41
+
42
+ seqpulse = SeqPulse(
43
+ api_key="sp_xxx",
44
+ endpoint="/seqpulse-metrics",
45
+ hmac_enabled=True,
46
+ hmac_secret="hmac_xxx",
47
+ )
48
+
49
+ app.middleware("http")(seqpulse.middleware())
50
+ ```
51
+
52
+ ## Returned payload
53
+
54
+ `GET /seqpulse-metrics` returns:
55
+
56
+ ```json
57
+ {
58
+ "metrics": {
59
+ "requests_per_sec": 0.25,
60
+ "latency_p95": 31.221,
61
+ "error_rate": 0,
62
+ "cpu_usage": 0.42,
63
+ "memory_usage": 0.18
64
+ }
65
+ }
66
+ ```
67
+
68
+ ## Notes
69
+
70
+ - This SDK does not manage CI/CD trigger/finish workflow.
71
+ - `api_key` is required for config consistency, but not used directly in endpoint responses.
72
+
73
+ ## Local smoke test
74
+
75
+ ```bash
76
+ python scripts/smoke.py
77
+ ```
@@ -0,0 +1,58 @@
1
+ # seqpulse (Python SDK)
2
+
3
+ SeqPulse SDK for:
4
+
5
+ - HTTP metrics instrumentation
6
+ - metrics endpoint exposure
7
+ - optional HMAC v2 validation on inbound SeqPulse calls
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install seqpulse
13
+ ```
14
+
15
+ ## FastAPI usage
16
+
17
+ ```python
18
+ from fastapi import FastAPI
19
+ from seqpulse import SeqPulse
20
+
21
+ app = FastAPI()
22
+
23
+ seqpulse = SeqPulse(
24
+ api_key="sp_xxx",
25
+ endpoint="/seqpulse-metrics",
26
+ hmac_enabled=True,
27
+ hmac_secret="hmac_xxx",
28
+ )
29
+
30
+ app.middleware("http")(seqpulse.middleware())
31
+ ```
32
+
33
+ ## Returned payload
34
+
35
+ `GET /seqpulse-metrics` returns:
36
+
37
+ ```json
38
+ {
39
+ "metrics": {
40
+ "requests_per_sec": 0.25,
41
+ "latency_p95": 31.221,
42
+ "error_rate": 0,
43
+ "cpu_usage": 0.42,
44
+ "memory_usage": 0.18
45
+ }
46
+ }
47
+ ```
48
+
49
+ ## Notes
50
+
51
+ - This SDK does not manage CI/CD trigger/finish workflow.
52
+ - `api_key` is required for config consistency, but not used directly in endpoint responses.
53
+
54
+ ## Local smoke test
55
+
56
+ ```bash
57
+ python scripts/smoke.py
58
+ ```
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "seqpulse"
7
+ version = "0.1.0"
8
+ description = "SeqPulse SDK for metrics endpoint instrumentation and HMAC validation"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ authors = [
13
+ { name = "Nassir" }
14
+ ]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Framework :: FastAPI",
21
+ "Topic :: Software Development :: Libraries :: Python Modules"
22
+ ]
23
+ dependencies = [
24
+ "psutil>=5.9.0",
25
+ "starlette>=0.36.0"
26
+ ]
27
+
28
+ [tool.setuptools.packages.find]
29
+ where = ["."]
30
+ include = ["seqpulse*"]
@@ -0,0 +1,4 @@
1
+ from .core import SeqPulse
2
+ from .core import SeqPulse as SeqPulseMiddleware
3
+
4
+ __all__ = ["SeqPulse", "SeqPulseMiddleware"]
@@ -0,0 +1,204 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import hmac
5
+ import math
6
+ import os
7
+ import secrets
8
+ import time
9
+ from collections import deque
10
+ from dataclasses import dataclass
11
+ from datetime import datetime, timezone
12
+ from typing import Any, Callable
13
+
14
+ try:
15
+ import psutil
16
+ except ImportError: # pragma: no cover
17
+ psutil = None
18
+ from starlette.responses import JSONResponse
19
+
20
+
21
+ def _canonicalize_path(path: str) -> str:
22
+ if not path:
23
+ return "/"
24
+ if not path.startswith("/"):
25
+ path = f"/{path}"
26
+ if path != "/" and path.endswith("/"):
27
+ path = path[:-1]
28
+ return path
29
+
30
+
31
+ def _p95(values: list[float]) -> float:
32
+ if not values:
33
+ return 0.0
34
+ sorted_values = sorted(values)
35
+ index = int(math.floor(0.95 * (len(sorted_values) - 1)))
36
+ return sorted_values[index]
37
+
38
+
39
+ @dataclass
40
+ class _Sample:
41
+ at_ms: float
42
+ latency_ms: float
43
+ is_error: bool
44
+
45
+
46
+ class SeqPulse:
47
+ def __init__(
48
+ self,
49
+ api_key: str,
50
+ *,
51
+ endpoint: str = "/seqpulse-metrics",
52
+ hmac_enabled: bool = False,
53
+ hmac_secret: str | None = None,
54
+ window_seconds: int = 60,
55
+ max_skew_past_seconds: int = 300,
56
+ max_skew_future_seconds: int = 30,
57
+ debug: bool = False,
58
+ ) -> None:
59
+ if not api_key:
60
+ raise ValueError("api_key is required")
61
+ if hmac_enabled and not hmac_secret:
62
+ raise ValueError("hmac_secret is required when hmac_enabled=True")
63
+ if window_seconds <= 0:
64
+ raise ValueError("window_seconds must be positive")
65
+
66
+ self.api_key = api_key
67
+ self.endpoint = _canonicalize_path(endpoint)
68
+ self.hmac_enabled = bool(hmac_enabled)
69
+ self.hmac_secret = hmac_secret or ""
70
+ self.window_seconds = int(window_seconds)
71
+ self.max_skew_past_seconds = int(max_skew_past_seconds)
72
+ self.max_skew_future_seconds = int(max_skew_future_seconds)
73
+ self.debug = bool(debug)
74
+
75
+ self._samples: deque[_Sample] = deque()
76
+ self._nonces_seen_at_ms: dict[str, float] = {}
77
+
78
+ def _now_ms(self) -> float:
79
+ return time.time() * 1000.0
80
+
81
+ def _cleanup_samples(self) -> None:
82
+ cutoff = self._now_ms() - self.window_seconds * 1000.0
83
+ while self._samples and self._samples[0].at_ms < cutoff:
84
+ self._samples.popleft()
85
+
86
+ def _cleanup_nonces(self) -> None:
87
+ ttl_ms = (self.max_skew_past_seconds + self.max_skew_future_seconds) * 1000.0
88
+ cutoff = self._now_ms() - ttl_ms
89
+ stale = [nonce for nonce, seen_ms in self._nonces_seen_at_ms.items() if seen_ms < cutoff]
90
+ for nonce in stale:
91
+ del self._nonces_seen_at_ms[nonce]
92
+
93
+ def _metrics_snapshot(self) -> dict[str, float]:
94
+ self._cleanup_samples()
95
+ samples = list(self._samples)
96
+ sample_count = len(samples)
97
+ latencies = [sample.latency_ms for sample in samples]
98
+ errors = sum(1 for sample in samples if sample.is_error)
99
+
100
+ if psutil is not None:
101
+ cpu = max(0.0, min(psutil.cpu_percent(interval=None) / 100.0, 1.0))
102
+ mem = max(0.0, min(psutil.virtual_memory().percent / 100.0, 1.0))
103
+ else:
104
+ cpu = 0.0
105
+ mem = 0.0
106
+
107
+ return {
108
+ "requests_per_sec": round(sample_count / self.window_seconds, 3),
109
+ "latency_p95": round(_p95(latencies), 3),
110
+ "error_rate": round((errors / sample_count), 6) if sample_count > 0 else 0.0,
111
+ "cpu_usage": round(cpu, 6),
112
+ "memory_usage": round(mem, 6),
113
+ }
114
+
115
+ def _build_signature(self, timestamp: str, method: str, path: str, nonce: str) -> str:
116
+ payload = f"{timestamp}|{method.upper()}|{_canonicalize_path(path)}|{nonce}"
117
+ digest = hmac.new(self.hmac_secret.encode(), payload.encode(), hashlib.sha256).hexdigest()
118
+ return f"sha256={digest}"
119
+
120
+ def _validate_timestamp(self, ts: str) -> None:
121
+ sent = datetime.fromisoformat(ts.replace("Z", "+00:00"))
122
+ now = datetime.now(timezone.utc)
123
+ delta = (now - sent).total_seconds()
124
+ if delta > self.max_skew_past_seconds:
125
+ raise ValueError("Timestamp too old")
126
+ if delta < -self.max_skew_future_seconds:
127
+ raise ValueError("Timestamp too far in the future")
128
+
129
+ def _validate_hmac_request(self, request: Any) -> tuple[bool, str | None]:
130
+ if not self.hmac_enabled:
131
+ return True, None
132
+
133
+ timestamp = request.headers.get("X-SeqPulse-Timestamp", "")
134
+ signature = request.headers.get("X-SeqPulse-Signature", "")
135
+ nonce = request.headers.get("X-SeqPulse-Nonce", "")
136
+ version = request.headers.get("X-SeqPulse-Signature-Version", "")
137
+ method = (request.headers.get("X-SeqPulse-Method") or request.method or "GET").upper()
138
+ path = _canonicalize_path(
139
+ request.headers.get("X-SeqPulse-Canonical-Path") or request.url.path or "/"
140
+ )
141
+
142
+ if not timestamp or not signature or not nonce or version != "v2":
143
+ return False, "Missing or invalid HMAC headers"
144
+
145
+ try:
146
+ self._validate_timestamp(timestamp)
147
+ except Exception as exc:
148
+ return False, str(exc)
149
+
150
+ self._cleanup_nonces()
151
+ if nonce in self._nonces_seen_at_ms:
152
+ return False, "Nonce reuse"
153
+
154
+ expected = self._build_signature(timestamp=timestamp, method=method, path=path, nonce=nonce)
155
+ if not hmac.compare_digest(expected, signature):
156
+ return False, "Invalid signature"
157
+
158
+ self._nonces_seen_at_ms[nonce] = self._now_ms()
159
+ return True, None
160
+
161
+ def middleware(self) -> Callable:
162
+ async def _middleware(request: Any, call_next: Callable) -> Any:
163
+ request_path = _canonicalize_path(request.url.path)
164
+ request_method = (request.method or "GET").upper()
165
+
166
+ if request_path == self.endpoint and request_method == "GET":
167
+ is_valid, reason = self._validate_hmac_request(request)
168
+ if not is_valid:
169
+ return JSONResponse(status_code=401, content={"error": reason or "Unauthorized"})
170
+ return JSONResponse(content={"metrics": self._metrics_snapshot()})
171
+
172
+ started_at = time.perf_counter()
173
+ response = await call_next(request)
174
+ latency_ms = (time.perf_counter() - started_at) * 1000.0
175
+ self._samples.append(
176
+ _Sample(
177
+ at_ms=self._now_ms(),
178
+ latency_ms=latency_ms,
179
+ is_error=response.status_code >= 500,
180
+ )
181
+ )
182
+ self._cleanup_samples()
183
+ return response
184
+
185
+ return _middleware
186
+
187
+ def capture_http_metrics(self) -> Callable:
188
+ return self.middleware()
189
+
190
+ def metrics_handler(self) -> Callable:
191
+ async def _handler(request: Any) -> JSONResponse:
192
+ is_valid, reason = self._validate_hmac_request(request)
193
+ if not is_valid:
194
+ return JSONResponse(status_code=401, content={"error": reason or "Unauthorized"})
195
+ return JSONResponse(content={"metrics": self._metrics_snapshot()})
196
+
197
+ return _handler
198
+
199
+ @staticmethod
200
+ def generate_nonce() -> str:
201
+ return secrets.token_urlsafe(16)
202
+
203
+
204
+ __all__ = ["SeqPulse"]
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.4
2
+ Name: seqpulse
3
+ Version: 0.1.0
4
+ Summary: SeqPulse SDK for metrics endpoint instrumentation and HMAC validation
5
+ Author: Nassir
6
+ License-Expression: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Framework :: FastAPI
12
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: psutil>=5.9.0
17
+ Requires-Dist: starlette>=0.36.0
18
+ Dynamic: license-file
19
+
20
+ # seqpulse (Python SDK)
21
+
22
+ SeqPulse SDK for:
23
+
24
+ - HTTP metrics instrumentation
25
+ - metrics endpoint exposure
26
+ - optional HMAC v2 validation on inbound SeqPulse calls
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ pip install seqpulse
32
+ ```
33
+
34
+ ## FastAPI usage
35
+
36
+ ```python
37
+ from fastapi import FastAPI
38
+ from seqpulse import SeqPulse
39
+
40
+ app = FastAPI()
41
+
42
+ seqpulse = SeqPulse(
43
+ api_key="sp_xxx",
44
+ endpoint="/seqpulse-metrics",
45
+ hmac_enabled=True,
46
+ hmac_secret="hmac_xxx",
47
+ )
48
+
49
+ app.middleware("http")(seqpulse.middleware())
50
+ ```
51
+
52
+ ## Returned payload
53
+
54
+ `GET /seqpulse-metrics` returns:
55
+
56
+ ```json
57
+ {
58
+ "metrics": {
59
+ "requests_per_sec": 0.25,
60
+ "latency_p95": 31.221,
61
+ "error_rate": 0,
62
+ "cpu_usage": 0.42,
63
+ "memory_usage": 0.18
64
+ }
65
+ }
66
+ ```
67
+
68
+ ## Notes
69
+
70
+ - This SDK does not manage CI/CD trigger/finish workflow.
71
+ - `api_key` is required for config consistency, but not used directly in endpoint responses.
72
+
73
+ ## Local smoke test
74
+
75
+ ```bash
76
+ python scripts/smoke.py
77
+ ```
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ seqpulse/__init__.py
5
+ seqpulse/core.py
6
+ seqpulse.egg-info/PKG-INFO
7
+ seqpulse.egg-info/SOURCES.txt
8
+ seqpulse.egg-info/dependency_links.txt
9
+ seqpulse.egg-info/requires.txt
10
+ seqpulse.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ psutil>=5.9.0
2
+ starlette>=0.36.0
@@ -0,0 +1 @@
1
+ seqpulse
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+