mettr 0.1.0__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.
mettr/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ """
2
+ mettr for Python: live analytics for websites and SaaS products. The client
3
+ sends the app's own events, crawlers' visits, 404s, exceptions and
4
+ subscriptions; mettr.django, mettr.starlette (FastAPI too) and mettr.flask
5
+ send what a request shows on their own.
6
+ """
7
+
8
+ from mettr._client import VERSION, Event, Mettr, Props, ProxyResponse, Visitor
9
+ from mettr._ip import forwarded_for, visitor_ip
10
+ from mettr._transport import Transport, UrllibTransport
11
+
12
+ __all__ = [
13
+ "VERSION",
14
+ "Event",
15
+ "Mettr",
16
+ "Props",
17
+ "ProxyResponse",
18
+ "Transport",
19
+ "UrllibTransport",
20
+ "Visitor",
21
+ "forwarded_for",
22
+ "visitor_ip",
23
+ ]
mettr/_client.py ADDED
@@ -0,0 +1,464 @@
1
+ """mettr's client: collects events and sends them in batches, so a request never waits on mettr."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import atexit
6
+ import fnmatch
7
+ import html
8
+ import json
9
+ import os
10
+ import random as _random
11
+ import re
12
+ import threading
13
+ import time
14
+ from collections.abc import Callable, Iterable, Mapping, Sequence
15
+ from dataclasses import dataclass, replace
16
+ from datetime import datetime, timezone
17
+ from typing import Any
18
+ from urllib.parse import urlsplit
19
+
20
+ from mettr import _contract as contract
21
+ from mettr._transport import Transport, UrllibTransport
22
+
23
+ VERSION = "0.1.0"
24
+
25
+ Props = Mapping[str, "str | int | float | bool | None"]
26
+ Event = dict[str, Any]
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Visitor:
31
+ """What the current request knows of the visitor. mettr uses the address
32
+ for the place and the visitor hash, and keeps nothing of it."""
33
+
34
+ url: str | None = None
35
+ ip: str | None = None
36
+ user_agent: str | None = None
37
+ user_id: str | None = None
38
+ #: Staff (the site's own people): nothing of theirs is sent.
39
+ staff: bool = False
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class ProxyResponse:
44
+ status: int
45
+ headers: dict[str, str]
46
+ body: str
47
+
48
+
49
+ def _flag(value: str | None) -> bool | None:
50
+ if value is None or value == "":
51
+ return None
52
+
53
+ return value.lower() in ("1", "true", "yes", "on")
54
+
55
+
56
+ def _moment(moment: datetime | None) -> str | None:
57
+ if moment is None:
58
+ return None
59
+
60
+ if moment.tzinfo is None:
61
+ moment = moment.replace(tzinfo=timezone.utc)
62
+
63
+ return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
64
+
65
+
66
+ def _defined(values: Mapping[str, Any]) -> dict[str, Any]:
67
+ return {key: value for key, value in values.items() if value is not None}
68
+
69
+
70
+ def _chunks(items: Sequence[Any], size: int) -> Iterable[Sequence[Any]]:
71
+ for start in range(0, len(items), size):
72
+ yield items[start : start + size]
73
+
74
+
75
+ _UNSET: Any = object()
76
+
77
+
78
+ class Mettr:
79
+ """
80
+ Sending never raises into the app: a failed batch answers False and is told
81
+ to on_error, without its events.
82
+ """
83
+
84
+ def __init__(
85
+ self,
86
+ secret_key: str | None = None,
87
+ public_key: str | None = None,
88
+ *,
89
+ endpoint: str | None = None,
90
+ enabled: bool | None = None,
91
+ proxy_path: str | None = _UNSET,
92
+ timeout: float = contract.TIMEOUT_SECONDS,
93
+ flush_interval: float = 1.0,
94
+ response_time_sample: float = contract.RESPONSE_TIME_SAMPLE,
95
+ crawler_pattern: re.Pattern[str] = contract.CRAWLER_PATTERN,
96
+ ignore: Sequence[str] = ("/up",),
97
+ track_not_found: bool = True,
98
+ track_exceptions: bool = True,
99
+ track_crawlers: bool = True,
100
+ transport: Transport | None = None,
101
+ on_error: Callable[[str], None] | None = None,
102
+ random: Callable[[], float] = _random.random,
103
+ ) -> None:
104
+ """
105
+ Settings come from the environment (METTR_SECRET_KEY, METTR_PUBLIC_KEY,
106
+ METTR_ENDPOINT, METTR_ENABLED, METTR_PROXY_PATH); arguments win. mettr
107
+ is on when METTR_ENABLED says so, or else once a key is set.
108
+
109
+ flush_interval: seconds events wait to go together, sent from a
110
+ background thread; 0 sends only on flush(), what a serverless
111
+ function calls before it ends.
112
+ """
113
+ env = os.environ
114
+ proxy = env.get("METTR_PROXY_PATH", contract.PROXY_PATH) if proxy_path is _UNSET else proxy_path
115
+
116
+ self.secret_key = secret_key if secret_key is not None else env.get("METTR_SECRET_KEY")
117
+ self.public_key = public_key if public_key is not None else env.get("METTR_PUBLIC_KEY")
118
+ self.endpoint = (endpoint or env.get("METTR_ENDPOINT") or contract.DEFAULT_ENDPOINT).rstrip("/")
119
+ told = _flag(env.get("METTR_ENABLED")) if enabled is None else enabled
120
+ self.enabled = told if told is not None else bool(self.secret_key or self.public_key)
121
+ self.proxy_path = (proxy.strip("/") or None) if proxy else None
122
+ self.timeout = timeout
123
+ self.flush_interval = flush_interval
124
+ self.response_time_sample = response_time_sample
125
+ self.crawler_pattern = crawler_pattern
126
+ self.ignore = tuple(ignore)
127
+ self.track_not_found = track_not_found
128
+ self.track_exceptions = track_exceptions
129
+ self.track_crawlers = track_crawlers
130
+ self._transport: Transport = transport or UrllibTransport()
131
+ self._on_error = on_error
132
+ self._random = random
133
+ self._lock = threading.Lock()
134
+ self._events: list[Event] = []
135
+ self._subscriptions: list[Event] = []
136
+ self._timer: threading.Timer | None = None
137
+ self._script: tuple[str, float] | None = None
138
+ atexit.register(self.flush)
139
+
140
+ # Events ---------------------------------------------------------------
141
+
142
+ def event(self, name: str, props: Props | None = None, visitor: Visitor | None = None) -> None:
143
+ """A custom event: mettr.event("signup", {"plan": "pro"}, Visitor(user_id="42"))."""
144
+ self.record({"type": "event", "name": name, "props": props}, visitor)
145
+
146
+ def error(self, name: str, props: Props | None = None, visitor: Visitor | None = None) -> None:
147
+ """An error: a 404, an exception, anything that broke."""
148
+ self.record({"type": "error", "name": name, "props": props}, visitor)
149
+
150
+ def exception(self, error: BaseException, visitor: Visitor | None = None) -> None:
151
+ """
152
+ An exception as an error event: its class only, never the message (it
153
+ may hold what the app's users typed). A client's error (a status under
154
+ 500: not found, a bad request) is the request's fault, not the app's.
155
+ """
156
+ status = getattr(error, "status_code", None)
157
+ status = getattr(error, "code", None) if status is None else status
158
+
159
+ if not self.track_exceptions or (isinstance(status, int) and status < 500):
160
+ return
161
+
162
+ self.error("exception", {"class": type(error).__name__}, visitor)
163
+
164
+ def revenue(
165
+ self, name: str, amount: float, currency: str, props: Props | None = None, visitor: Visitor | None = None
166
+ ) -> None:
167
+ """A payment: an amount in the currency's main unit, negative for a refund."""
168
+ self.record(
169
+ {"type": "revenue", "name": name, "revenue": {"amount": amount, "currency": currency}, "props": props},
170
+ visitor,
171
+ )
172
+
173
+ def crawl(self, status: int, visitor: Visitor) -> None:
174
+ """A crawler's request: the page and its status. mettr names the crawler."""
175
+ self.record({"type": "crawl", "props": {"status": status}}, visitor)
176
+
177
+ def record(self, event: Event, visitor: Visitor | None = None) -> None:
178
+ """
179
+ Adds an event with what the request knows of the visitor. Nothing is
180
+ added while mettr is off, for staff, or on a path mettr ignores.
181
+ """
182
+ visitor = visitor or Visitor()
183
+
184
+ if not self.enabled or visitor.staff or self.ignores(visitor.url):
185
+ return
186
+
187
+ props = event.get("props")
188
+ kept = _defined(
189
+ {
190
+ **event,
191
+ # An event that says its own address keeps it, even none.
192
+ "url": event.get("url", visitor.url),
193
+ "ip": event.get("ip") or visitor.ip,
194
+ "user_agent": event.get("user_agent") or visitor.user_agent,
195
+ # A crawl is nobody's (mettr refuses one with a user).
196
+ "user_id": None if event.get("type") == "crawl" else event.get("user_id") or visitor.user_id,
197
+ "props": dict(props) if props else None,
198
+ }
199
+ )
200
+
201
+ with self._lock:
202
+ self._events.append(kept)
203
+ full = len(self._events) >= contract.BATCH
204
+
205
+ self._schedule(full)
206
+
207
+ def subscription(
208
+ self,
209
+ id: str,
210
+ status: str,
211
+ amount: float,
212
+ currency: str,
213
+ *,
214
+ interval: str = "month",
215
+ interval_count: int = 1,
216
+ user_id: str | None = None,
217
+ plan: str | None = None,
218
+ started_at: datetime | None = None,
219
+ canceled_at: datetime | None = None,
220
+ changed_at: datetime | None = None,
221
+ ) -> None:
222
+ """
223
+ A subscription of the app's own billing, as it is now, for MRR when
224
+ mettr does not read the billing itself (not Stripe, Paddle or Polar).
225
+ Send it whenever it changes, and every subscription once for the
226
+ history. status: active or past_due (both pay), trialing, paused,
227
+ canceled; amount: each cycle, before tax, in the main unit.
228
+ """
229
+ if not self.enabled:
230
+ return
231
+
232
+ item = _defined(
233
+ {
234
+ "id": id,
235
+ "status": status,
236
+ "amount": amount,
237
+ "currency": currency,
238
+ "interval": interval,
239
+ "interval_count": interval_count,
240
+ "user_id": user_id,
241
+ "plan": plan,
242
+ "started_at": _moment(started_at),
243
+ "canceled_at": _moment(canceled_at),
244
+ "changed_at": _moment(changed_at),
245
+ }
246
+ )
247
+
248
+ with self._lock:
249
+ self._subscriptions.append(item)
250
+
251
+ self._schedule(False)
252
+
253
+ # Sending --------------------------------------------------------------
254
+
255
+ def flush(self) -> bool:
256
+ """Sends what has been collected, now; what a serverless function calls before it ends."""
257
+ with self._lock:
258
+ if self._timer is not None:
259
+ self._timer.cancel()
260
+ self._timer = None
261
+
262
+ events, self._events = self._events, []
263
+ subscriptions, self._subscriptions = self._subscriptions, []
264
+
265
+ sent_events = not events or self.send(events)
266
+ sent_subscriptions = not subscriptions or self._post(
267
+ contract.PATHS["subscriptions"], "subscriptions", subscriptions, contract.SUBSCRIPTIONS_BATCH
268
+ )
269
+
270
+ return sent_events and sent_subscriptions
271
+
272
+ def send(self, events: Sequence[Event]) -> bool:
273
+ """Sends events now, in batches of 100, as mettr's ingest API takes them."""
274
+ return self._post(contract.PATHS["events"], "events", events, contract.BATCH)
275
+
276
+ def import_events(self, events: Sequence[Event]) -> bool:
277
+ """History (POST /api/v1/import), in batches of 1,000: each with ts and source_id."""
278
+ return self._post(contract.PATHS["import"], "events", events, contract.IMPORT_BATCH)
279
+
280
+ def annotation(self, title: str, *, url: str | None = None, ts: datetime | None = None) -> bool:
281
+ """A change under the traffic chart, from a deploy script or CI."""
282
+ return self._request(contract.PATHS["annotations"], _defined({"title": title, "url": url, "ts": _moment(ts)}))
283
+
284
+ def _schedule(self, now: bool) -> None:
285
+ if now:
286
+ self.flush()
287
+
288
+ return
289
+
290
+ if self.flush_interval <= 0:
291
+ return
292
+
293
+ with self._lock:
294
+ if self._timer is not None:
295
+ return
296
+
297
+ self._timer = threading.Timer(self.flush_interval, self.flush)
298
+ # A waiting batch never keeps the process alive; atexit sends it.
299
+ self._timer.daemon = True
300
+ self._timer.start()
301
+
302
+ def _post(self, path: str, key: str, items: Sequence[Event], size: int) -> bool:
303
+ if not items:
304
+ return False
305
+
306
+ # A list, not a generator: every batch is sent, even after one fails.
307
+ return all([self._request(path, {key: list(batch)}) for batch in _chunks(items, size)]) # noqa: C419
308
+
309
+ def _request(self, path: str, body: Mapping[str, Any]) -> bool:
310
+ if not self.secret_key:
311
+ return False
312
+
313
+ status = self._transport.post(
314
+ self.endpoint + path,
315
+ json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8"),
316
+ {
317
+ "Authorization": f"Bearer {self.secret_key}",
318
+ "Content-Type": "application/json",
319
+ "Accept": "application/json",
320
+ "User-Agent": f"mettr-python/{VERSION}",
321
+ },
322
+ self.timeout,
323
+ )
324
+
325
+ if 200 <= status < 300:
326
+ return True
327
+
328
+ if self._on_error is not None:
329
+ self._on_error(f"mettr answered {status} on {path}" if status else f"mettr could not be reached on {path}")
330
+
331
+ return False
332
+
333
+ # The middleware's side ------------------------------------------------
334
+
335
+ def is_crawler(self, user_agent: str | None) -> bool:
336
+ """Whether a user agent is a crawler's, as the middleware reads it."""
337
+ return self.track_crawlers and bool(user_agent) and self.crawler_pattern.search(user_agent or "") is not None
338
+
339
+ def ignores(self, url: str | None) -> bool:
340
+ """Whether a URL or path is one mettr sends nothing for (a * matches anything)."""
341
+ if url is None:
342
+ return False
343
+
344
+ path = urlsplit(url).path or "/"
345
+
346
+ return any(fnmatch.fnmatchcase(path, "/" + pattern.lstrip("/")) for pattern in self.ignore)
347
+
348
+ def is_proxy(self, path: str | None) -> bool:
349
+ """Whether a path is under the proxy path."""
350
+ if self.proxy_path is None or path is None:
351
+ return False
352
+
353
+ return (urlsplit(path).path or "/").startswith(f"/{self.proxy_path}/")
354
+
355
+ def finished(self, status: int, ms: float, route: str | None, visitor: Visitor) -> None:
356
+ """
357
+ What a framework's middleware calls once the response is known: a
358
+ crawler's request becomes a crawl, a 404 an error, and a sample of
359
+ requests sends its response time. mettr's own proxy path sends none.
360
+ """
361
+ if self.is_proxy(visitor.url):
362
+ return
363
+
364
+ if self.is_crawler(visitor.user_agent):
365
+ # Its status says a 404 too: no error beside it.
366
+ self.crawl(status, visitor)
367
+ elif status == 404 and self.track_not_found:
368
+ self.error("404", None, visitor)
369
+
370
+ if self.response_time_sample > 0 and self._random() < self.response_time_sample:
371
+ self.event("response_time", {"ms": round(ms), "route": route or "(none)", "status": status}, visitor)
372
+
373
+ def script_attributes(self) -> dict[str, str] | None:
374
+ """The script tag's attributes, or None while mettr is off."""
375
+ if not self.enabled or not self.public_key:
376
+ return None
377
+
378
+ if self.proxy_path is None:
379
+ return {"data-key": self.public_key, "src": self.endpoint + contract.PATHS["script"]}
380
+
381
+ return {
382
+ "data-key": self.public_key,
383
+ "data-api": f"/{self.proxy_path}/events",
384
+ "src": f"/{self.proxy_path}/script.js",
385
+ }
386
+
387
+ def script_tag(self) -> str:
388
+ """The tag for the page's <head>: the script with the site's public key; empty while mettr is off."""
389
+ attributes = self.script_attributes()
390
+
391
+ if attributes is None:
392
+ return ""
393
+
394
+ return (
395
+ "<script defer"
396
+ + "".join(f' {name}="{html.escape(value)}"' for name, value in attributes.items())
397
+ + "></script>"
398
+ )
399
+
400
+ def proxy_script(self) -> ProxyResponse:
401
+ """
402
+ GET {proxy}/script.js: mettr's browser script from your own domain,
403
+ fetched once an hour and kept in memory. While mettr cannot be reached
404
+ the page gets an empty script, tried again in a minute.
405
+ """
406
+ now = time.monotonic()
407
+ cached = self._script
408
+
409
+ if cached is None or cached[1] <= now:
410
+ status, body = self._transport.get(self.endpoint + contract.PATHS["script"], self.timeout)
411
+
412
+ if not 200 <= status < 300:
413
+ return self._javascript("/* mettr is unavailable */", contract.SCRIPT_RETRY_SECONDS)
414
+
415
+ cached = self._script = (body, now + contract.SCRIPT_CACHE_SECONDS)
416
+
417
+ return self._javascript(cached[0], contract.SCRIPT_CACHE_SECONDS)
418
+
419
+ def proxy_events(self, raw: bytes | str, visitor: Visitor) -> tuple[int, dict[str, Any]]:
420
+ """
421
+ POST {proxy}/events: the browser script's events, through your own
422
+ domain. They go on with the secret key, carrying what only your server
423
+ knows: the visitor's address and browser as they reached you, and the
424
+ signed-in user. So only what a browser may say passes: the types and
425
+ fields of the public key, never a time, a user, an address or revenue.
426
+ """
427
+ data = raw.encode("utf-8") if isinstance(raw, str) else raw
428
+
429
+ if len(data) > contract.PROXY_MAX_BYTES:
430
+ return 413, {"message": "The body is too large."}
431
+
432
+ try:
433
+ body = json.loads(data)
434
+ except ValueError:
435
+ body = None
436
+
437
+ if not self.public_key or not isinstance(body, dict) or body.get("key") != self.public_key:
438
+ return 403, {"message": "Not this site's key."}
439
+
440
+ items = body["events"] if isinstance(body.get("events"), list) else [body]
441
+ accepted = 0
442
+
443
+ for item in items[: contract.PROXY_MAX_EVENTS]:
444
+ if not isinstance(item, dict) or item.get("type") not in contract.PROXY_TYPES:
445
+ continue
446
+
447
+ kept = {field: value for field, value in item.items() if field in contract.PROXY_FIELDS}
448
+ kept["url"] = item.get("url") if isinstance(item.get("url"), str) else None
449
+ self.record(kept, visitor)
450
+ accepted += 1
451
+
452
+ return 202, {"accepted": accepted}
453
+
454
+ def with_visitor(self, visitor: Visitor, **changes: Any) -> Visitor:
455
+ """A visitor with some fields changed (the user once auth has run)."""
456
+ return replace(visitor, **changes)
457
+
458
+ @staticmethod
459
+ def _javascript(body: str, max_age: int) -> ProxyResponse:
460
+ return ProxyResponse(
461
+ 200,
462
+ {"Content-Type": "application/javascript; charset=utf-8", "Cache-Control": f"public, max-age={max_age}"},
463
+ body,
464
+ )
mettr/_contract.py ADDED
@@ -0,0 +1,53 @@
1
+ """What every mettr SDK shares: the app's resources/sdk-contract.json, copied
2
+ to this repository's sdk-contract.json (tests/test_contract.py holds the two
3
+ together)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+
9
+ DEFAULT_ENDPOINT = "https://mettr.app"
10
+
11
+ PATHS = {
12
+ "events": "/api/v1/events",
13
+ "import": "/api/v1/import",
14
+ "subscriptions": "/api/v1/subscriptions",
15
+ "annotations": "/api/v1/annotations",
16
+ "script": "/script.js",
17
+ }
18
+
19
+ BATCH = 100
20
+ IMPORT_BATCH = 1000
21
+ SUBSCRIPTIONS_BATCH = 100
22
+ MAX_PROPS = 30
23
+ MAX_PROP_LENGTH = 500
24
+
25
+ SUBSCRIPTION_STATUSES = ("active", "trialing", "past_due", "paused", "canceled")
26
+ SUBSCRIPTION_INTERVALS = ("day", "week", "month", "year")
27
+
28
+ PROXY_PATH = "_live"
29
+ PROXY_MAX_BYTES = 65536
30
+ PROXY_MAX_EVENTS = 20
31
+ PROXY_TYPES = ("pageview", "event", "engagement", "vital", "presence")
32
+ PROXY_FIELDS = ("type", "name", "url", "referrer", "props", "automated")
33
+ SCRIPT_CACHE_SECONDS = 3600
34
+ SCRIPT_RETRY_SECONDS = 60
35
+
36
+ TIMEOUT_SECONDS = 3
37
+ RESPONSE_TIME_SAMPLE = 0.05
38
+
39
+ CRAWLER_PATTERN = re.compile(
40
+ "bot|crawl|spider|slurp|facebookexternalhit|facebookcatalog|embedly|iframely|whatsapp|perplexity|chatgpt"
41
+ "|claude|anthropic|cohere|diffbot|bytespider|meta-external|uptime|pingdom|statuscake|site24x7|checkly"
42
+ "|screaming frog",
43
+ re.IGNORECASE,
44
+ )
45
+
46
+ # Cloudflare's addresses, from cloudflare.com/ips (October 2026).
47
+ CLOUDFLARE = (
48
+ "173.245.48.0/20", "103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22", "141.101.64.0/18",
49
+ "108.162.192.0/18", "190.93.240.0/20", "188.114.96.0/20", "197.234.240.0/22", "198.41.128.0/17",
50
+ "162.158.0.0/15", "104.16.0.0/13", "104.24.0.0/14", "172.64.0.0/13", "131.0.72.0/22",
51
+ "2400:cb00::/32", "2606:4700::/32", "2803:f800::/32", "2405:b500::/32", "2405:8100::/32",
52
+ "2a06:98c0::/29", "2c0f:f248::/32",
53
+ ) # fmt: skip
mettr/_ip.py ADDED
@@ -0,0 +1,52 @@
1
+ """The visitor's address, not the edge node relaying the request."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ipaddress
6
+
7
+ from mettr._contract import CLOUDFLARE
8
+
9
+ _NETWORKS = tuple(ipaddress.ip_network(cidr) for cidr in CLOUDFLARE)
10
+
11
+
12
+ def _parse(address: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:
13
+ try:
14
+ parsed = ipaddress.ip_address(address.strip().split("%")[0])
15
+ except ValueError:
16
+ return None
17
+
18
+ # An IPv4 address as a dual-stack socket gives it (::ffff:203.0.113.7) is the IPv4 address.
19
+ if isinstance(parsed, ipaddress.IPv6Address) and parsed.ipv4_mapped is not None:
20
+ return parsed.ipv4_mapped
21
+
22
+ return parsed
23
+
24
+
25
+ def visitor_ip(relay: str | None, connecting: str | None) -> str | None:
26
+ """
27
+ Behind Cloudflare, the address the request came from (the relay) is a
28
+ Cloudflare node: every visitor would be placed where the node is, and
29
+ would become a new visitor whenever Cloudflare routed them through
30
+ another. CF-Connecting-IP names the address Cloudflare took the request
31
+ from, and counts only when the request came from Cloudflare: one sent to
32
+ the server directly could name any address.
33
+ """
34
+ source = _parse(relay) if relay else None
35
+
36
+ if source is None:
37
+ return relay or None
38
+
39
+ if connecting and any(source in network for network in _NETWORKS):
40
+ visitor = _parse(connecting)
41
+
42
+ if visitor is not None:
43
+ return str(visitor)
44
+
45
+ return str(source)
46
+
47
+
48
+ def forwarded_for(header: str | None) -> str | None:
49
+ """The first address of X-Forwarded-For: the client, as the proxies saw it."""
50
+ first = (header or "").split(",")[0].strip()
51
+
52
+ return first if first and _parse(first) is not None else None
mettr/_transport.py ADDED
@@ -0,0 +1,48 @@
1
+ """HTTP for the client, on the standard library: no dependency to clash with the app's."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import urllib.error
6
+ import urllib.request
7
+ from typing import Protocol
8
+
9
+
10
+ class Transport(Protocol):
11
+ def post(self, url: str, body: bytes, headers: dict[str, str], timeout: float) -> int:
12
+ """POST a body; the status mettr answered, or 0 when it could not be reached."""
13
+
14
+ def get(self, url: str, timeout: float) -> tuple[int, str]:
15
+ """GET a text; its status and body, or (0, "") when it could not be reached."""
16
+
17
+
18
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
19
+ # The key stays with mettr: a redirect is answered as its own status, never followed.
20
+ def redirect_request(self, *args: object, **kwargs: object) -> None:
21
+ return None
22
+
23
+
24
+ class UrllibTransport:
25
+ """TLS verified (urllib's default context), no redirects, a timeout on every call."""
26
+
27
+ def __init__(self) -> None:
28
+ self._opener = urllib.request.build_opener(_NoRedirect)
29
+
30
+ def post(self, url: str, body: bytes, headers: dict[str, str], timeout: float) -> int:
31
+ return self._open(url, "POST", body, headers, timeout)[0]
32
+
33
+ def get(self, url: str, timeout: float) -> tuple[int, str]:
34
+ return self._open(url, "GET", None, {}, timeout)
35
+
36
+ def _open(
37
+ self, url: str, method: str, body: bytes | None, headers: dict[str, str], timeout: float
38
+ ) -> tuple[int, str]:
39
+ try:
40
+ # Built inside: a malformed endpoint is a failure, never an exception in the app.
41
+ request = urllib.request.Request(url, data=body, headers=headers, method=method) # noqa: S310 (https by default)
42
+
43
+ with self._opener.open(request, timeout=timeout) as response:
44
+ return int(response.status), response.read().decode("utf-8")
45
+ except urllib.error.HTTPError as error:
46
+ return int(error.code), ""
47
+ except (OSError, ValueError):
48
+ return 0, ""
@@ -0,0 +1,13 @@
1
+ """
2
+ mettr for Django. In settings:
3
+
4
+ INSTALLED_APPS = [..., "mettr.django"]
5
+ MIDDLEWARE = [..., "django.contrib.auth.middleware.AuthenticationMiddleware", "mettr.django.MettrMiddleware", ...]
6
+
7
+ and {% load mettr %}{% mettr_script %} in the base template's <head>.
8
+ """
9
+
10
+ from mettr.django._client import get_mettr, reset_mettr, visitor
11
+ from mettr.django.middleware import MettrMiddleware
12
+
13
+ __all__ = ["MettrMiddleware", "get_mettr", "reset_mettr", "visitor"]