bugle-sdk 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.
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.4
2
+ Name: bugle-sdk
3
+ Version: 0.1.0
4
+ Summary: Automatic request reporting middleware for Bugle
5
+ Author: Joe Georgeo Slamie
6
+ Project-URL: Homepage, https://jgeeking.com/
7
+ Keywords: bugle,wsgi,middleware,monitoring,fly
8
+ Requires-Python: >=3.9
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.4
2
+ Name: bugle-sdk
3
+ Version: 0.1.0
4
+ Summary: Automatic request reporting middleware for Bugle
5
+ Author: Joe Georgeo Slamie
6
+ Project-URL: Homepage, https://jgeeking.com/
7
+ Keywords: bugle,wsgi,middleware,monitoring,fly
8
+ Requires-Python: >=3.9
@@ -0,0 +1,6 @@
1
+ bugle_sdk.py
2
+ pyproject.toml
3
+ bugle_sdk.egg-info/PKG-INFO
4
+ bugle_sdk.egg-info/SOURCES.txt
5
+ bugle_sdk.egg-info/dependency_links.txt
6
+ bugle_sdk.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ bugle_sdk
@@ -0,0 +1,153 @@
1
+ """Small WSGI middleware that reports every request to a Bugle server."""
2
+ import http.client
3
+ import json
4
+ import os
5
+ import socket
6
+ import threading
7
+ import time
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ from urllib.request import Request, urlopen
10
+
11
+ # Default Bugle URL so apps need no config. BUGLE_URL overrides it.
12
+ DEFAULT_BUGLE_URL = "https://buggle.fly.dev"
13
+ FLY_SOCKET = "/.fly/api"
14
+ AUDIENCE = "bugle"
15
+
16
+ _REPORTERS = ThreadPoolExecutor(max_workers=2, thread_name_prefix="bugle-beacon")
17
+ _token_lock = threading.Lock()
18
+ _token = {"value": "", "expires": 0.0}
19
+
20
+
21
+ class _FlySocket(http.client.HTTPConnection):
22
+ """HTTP over the Fly machine's local Unix socket."""
23
+
24
+ def connect(self):
25
+ self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
26
+ self.sock.settimeout(2)
27
+ self.sock.connect(FLY_SOCKET)
28
+
29
+
30
+ def _fly_identity_token():
31
+ """Short-lived, Fly-signed identity token for this machine (cached ~8 min).
32
+
33
+ Returns "" when not running on a Fly machine.
34
+ """
35
+ with _token_lock:
36
+ if _token["value"] and time.time() < _token["expires"]:
37
+ return _token["value"]
38
+ if not os.path.exists(FLY_SOCKET):
39
+ return ""
40
+ try:
41
+ conn = _FlySocket("localhost", timeout=2)
42
+ conn.request(
43
+ "POST",
44
+ "/v1/tokens/oidc",
45
+ json.dumps({"aud": AUDIENCE}),
46
+ {"Content-Type": "application/json"},
47
+ )
48
+ response = conn.getresponse()
49
+ value = response.read().decode("utf-8").strip().strip('"')
50
+ conn.close()
51
+ except Exception:
52
+ return ""
53
+ if response.status != 200 or not value:
54
+ return ""
55
+ _token["value"] = value
56
+ _token["expires"] = time.time() + 480 # Fly tokens last 10 minutes
57
+ return value
58
+
59
+
60
+ def _send(url, event, ingestion_key):
61
+ try:
62
+ headers = {"Content-Type": "application/json"}
63
+ if ingestion_key: # optional fallback for non-Fly testing
64
+ headers["X-Buggle-Key"] = ingestion_key
65
+ else:
66
+ token = _fly_identity_token()
67
+ if not token:
68
+ return
69
+ headers["Authorization"] = f"Bearer {token}"
70
+ request = Request(
71
+ url,
72
+ data=json.dumps(event, separators=(",", ":")).encode("utf-8"),
73
+ headers=headers,
74
+ method="POST",
75
+ )
76
+ with urlopen(request, timeout=2):
77
+ pass
78
+ except Exception:
79
+ # Reporting must never affect the application response.
80
+ pass
81
+
82
+
83
+ class BugleMiddleware:
84
+ """Wrap a WSGI app to report all requests, without editing route handlers.
85
+
86
+ On a Fly machine nothing needs configuring: the app, machine and org are proven
87
+ by a Fly-signed identity token. BUGLE_URL overrides the default Bugle URL, and
88
+ BUGLE_INGESTION_KEY is an optional shared-secret fallback for non-Fly testing.
89
+ """
90
+
91
+ def __init__(self, app, bugle_url=None, app_name=None, machine=None, ingestion_key=None):
92
+ self.app = app
93
+ self.url = (bugle_url or os.getenv("BUGLE_URL", "") or DEFAULT_BUGLE_URL).rstrip("/")
94
+ self.app_name = app_name or os.getenv("BUGLE_APP") or os.getenv("FLY_APP_NAME", "unknown")
95
+ self.machine = machine if machine is not None else os.getenv("FLY_MACHINE_ID", "")
96
+ self.ingestion_key = ingestion_key or os.getenv("BUGLE_INGESTION_KEY", "")
97
+
98
+ def __call__(self, environ, start_response):
99
+ if not self.url or not (self.ingestion_key or os.path.exists(FLY_SOCKET)):
100
+ return self.app(environ, start_response)
101
+
102
+ started = time.perf_counter()
103
+ status_code = 500
104
+
105
+ def capture_status(status, headers, exc_info=None):
106
+ nonlocal status_code
107
+ try:
108
+ status_code = int(status.split(" ", 1)[0])
109
+ except (ValueError, IndexError):
110
+ status_code = 500
111
+ return start_response(status, headers, exc_info)
112
+
113
+ try:
114
+ response = self.app(environ, capture_status)
115
+ except Exception:
116
+ self._report(environ, status_code, started)
117
+ raise
118
+
119
+ def report_on_close():
120
+ nonlocal reported
121
+ if reported:
122
+ return
123
+ reported = True
124
+ try:
125
+ close = getattr(response, "close", None)
126
+ if close:
127
+ close()
128
+ finally:
129
+ self._report(environ, status_code, started)
130
+
131
+ class ResponseIterator:
132
+ def __iter__(self):
133
+ return iter(response)
134
+
135
+ def close(self):
136
+ report_on_close()
137
+
138
+ reported = False
139
+ return ResponseIterator()
140
+
141
+ def _report(self, environ, status, started):
142
+ event = {
143
+ "app": self.app_name,
144
+ "machine": self.machine,
145
+ "method": environ.get("REQUEST_METHOD", ""),
146
+ "path": environ.get("PATH_INFO", ""),
147
+ "status": status,
148
+ "duration_ms": round((time.perf_counter() - started) * 1000),
149
+ }
150
+ try:
151
+ _REPORTERS.submit(_send, f"{self.url}/api/hit", event, self.ingestion_key)
152
+ except RuntimeError:
153
+ pass
@@ -0,0 +1,17 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "bugle-sdk"
7
+ version = "0.1.0"
8
+ description = "Automatic request reporting middleware for Bugle"
9
+ requires-python = ">=3.9"
10
+ authors = [{ name = "Joe Georgeo Slamie" }]
11
+ keywords = ["bugle", "wsgi", "middleware", "monitoring", "fly"]
12
+
13
+ [project.urls]
14
+ Homepage = "https://jgeeking.com/"
15
+
16
+ [tool.setuptools]
17
+ py-modules = ["bugle_sdk"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+