feralin-fastapi 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.
@@ -0,0 +1,8 @@
1
+ """Feralin FastAPI ara katmanı: `feralin` çekirdeği üstünde istek başına izin ve kimlik geçirme."""
2
+
3
+ from ._core import ConsentClientPool, RequestFeralin, clean_context
4
+ from .middleware import FeralinMiddleware, get_feralin
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ __all__ = ["ConsentClientPool", "FeralinMiddleware", "RequestFeralin", "clean_context", "get_feralin", "__version__"]
@@ -0,0 +1,188 @@
1
+ """Python ara katmanlarının ortak katmanı. Bu dosya sdks/python-django ve sdks/python-fastapi altında birebir aynıdır
2
+ (`feralin_*` paket adı dışında içe aktarma yoktur); her paketin testi eşitliği denetler.
3
+
4
+ Çekirdek `feralin.Client` izni istemci düzeyinde tutar. Sunucuda her istek farklı kullanıcıya aittir ve `set_consent`
5
+ paylaşılan durumu değiştirir; bu yüzden izin değeri başına ayrı istemci kullanılır (en çok 8 birleşim). Çekirdek değişmez.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import atexit
11
+ import ipaddress
12
+ import logging
13
+ import re
14
+ import threading
15
+ from collections.abc import Mapping
16
+ from dataclasses import dataclass
17
+ from typing import Any
18
+ from urllib.parse import quote, urlsplit
19
+
20
+ from feralin import Client, Consent, Context, FeralinError, FlushResult, UtpEvent
21
+
22
+ _log = logging.getLogger("feralin")
23
+
24
+ MAX_URL_LENGTH = 2048
25
+ MAX_LOCALE_LENGTH = 16
26
+
27
+ # İstekten gelen Host ve Referer saldırgan denetimindedir; toplayıcının `format: uri` denetimi (Go net/url) geçersiz adreste
28
+ # tüm batch'i 400 ile düşürür, başka kullanıcıların olayları da gider. Yalnız bu dar biçim kabul edilir, gerisi gönderilmez.
29
+ _AUTHORITY = re.compile(r"(?P<host>[A-Za-z0-9._~-]+|\[(?P<ipv6>[0-9A-Fa-f:.]+)\])(?::[0-9]{1,5})?")
30
+ _STRAY_PERCENT = re.compile(r"%(?![0-9A-Fa-f]{2})")
31
+ _LOCALE = re.compile(r"[A-Za-z0-9_-]+")
32
+
33
+
34
+ class ConsentClientPool:
35
+ """İzin değeri başına tembel kurulan istemciler. İzinsiz olay için istemci kurulmaz."""
36
+
37
+ def __init__(self, project_key: str, collect_url: str, **client_options: Any) -> None:
38
+ client_options.pop("consent", None)
39
+ self._project_key = project_key
40
+ self._collect_url = collect_url
41
+ self._options = client_options
42
+ self._lock = threading.Lock()
43
+ self._clients: dict[Consent, Client] = {}
44
+ self._closed = False
45
+ # Yapılandırma hatası uygulama açılışında fırlasın (sk_ anahtar, geçersiz adres); istek anında değil.
46
+ Client(project_key, collect_url, flush_interval=0, transport=client_options.get("transport")).close(timeout=0)
47
+ atexit.register(self.close)
48
+
49
+ def client_for(self, consent: Consent) -> Client | None:
50
+ if not consent.analytics:
51
+ return None
52
+ with self._lock:
53
+ if self._closed:
54
+ return None
55
+ client = self._clients.get(consent)
56
+ if client is None:
57
+ client = Client(self._project_key, self._collect_url, consent=consent, **self._options)
58
+ self._clients[consent] = client
59
+ return client
60
+
61
+ def track(self, consent: Consent, event_name: str, properties: Mapping[str, Any] | None = None, **fields: Any) -> UtpEvent | None:
62
+ """Fırlatmaz: izin yoksa veya girdi geçersizse None döner, geçersiz girdi uyarı olarak loglanır."""
63
+ client = self.client_for(consent)
64
+ if client is None:
65
+ return None
66
+ try:
67
+ return client.track(event_name, properties, **fields)
68
+ except FeralinError as exc:
69
+ _log.warning("feralin: olay üretilemedi: %s", type(exc).__name__)
70
+ return None
71
+
72
+ def flush(self) -> FlushResult:
73
+ """Tüm istemcileri gönderir; sayılar toplanır, durum ve batch_id son gönderimindir, hata ilk hatadır."""
74
+ with self._lock:
75
+ clients = list(self._clients.values())
76
+ total = FlushResult()
77
+ for client in clients:
78
+ try:
79
+ total = _merge(total, client.flush())
80
+ except FeralinError as exc:
81
+ _log.warning("feralin: gönderim yapılamadı: %s", type(exc).__name__)
82
+ return total
83
+
84
+ def close(self, timeout: float = 5.0) -> None:
85
+ """Kuyrukları göndermeyi dener. Birden çok çağrı güvenlidir; süreç çıkışında da çalışır."""
86
+ with self._lock:
87
+ if self._closed:
88
+ return
89
+ self._closed = True
90
+ clients = list(self._clients.values())
91
+ atexit.unregister(self.close)
92
+ for client in clients:
93
+ client.close(timeout=timeout)
94
+
95
+
96
+ def _merge(a: FlushResult, b: FlushResult) -> FlushResult:
97
+ return FlushResult(
98
+ sent=a.sent + b.sent,
99
+ accepted=a.accepted + b.accepted,
100
+ rejected=a.rejected + b.rejected,
101
+ batch_id=b.batch_id or a.batch_id,
102
+ status=b.status or a.status,
103
+ retained=a.retained + b.retained,
104
+ error=a.error or b.error,
105
+ )
106
+
107
+
108
+ @dataclass(frozen=True)
109
+ class RequestFeralin:
110
+ """O isteğe bağlı yüzey: izin, kimlik ve bağlam her olaya otomatik eklenir."""
111
+
112
+ pool: ConsentClientPool | None
113
+ consent: Consent
114
+ user_id: str | None = None
115
+ anonymous_id: str | None = None
116
+ session_id: str | None = None
117
+ context: Context | None = None
118
+
119
+ def track(self, event_name: str, properties: Mapping[str, Any] | None = None, **fields: Any) -> UtpEvent | None:
120
+ if self.pool is None:
121
+ return None
122
+ merged: dict[str, Any] = {"user_id": self.user_id, "anonymous_id": self.anonymous_id, "session_id": self.session_id, "context": self.context}
123
+ merged.update(fields)
124
+ return self.pool.track(self.consent, event_name, properties, **merged)
125
+
126
+ def flush(self) -> FlushResult:
127
+ """Ağa çıkar ve bekler. Normalde arka plan göndericisi yeterlidir; asenkron görünümde iş parçacığına alın."""
128
+ return self.pool.flush() if self.pool is not None else FlushResult()
129
+
130
+
131
+ def clean_context(scheme: str | None, host: str | None, path: str | None, referrer: str | None, accept_language: str | None) -> Context | None:
132
+ """Çekirdek URL temizlemez: sorgu ve parça burada atılır, referrer yalnız origin kalır. Şemaya uymayan alan kırpılmaz,
133
+ gönderilmez: kırpılmış adres yanlış veridir, tek geçersiz alan ise toplayıcıda tüm batch'i 400 ile düşürür.
134
+ IP, User-Agent ve çerez okunmaz."""
135
+ page_url = None
136
+ if scheme in ("http", "https") and host and path is not None and _valid_authority(host):
137
+ # Çerçeveler yolu çözülmüş verir; açıkta kalan % kaçış sanılıp adresi geçersiz kılmasın diye kodlanır.
138
+ encoded = quote(_STRAY_PERCENT.sub("%25", path), safe="/%:@!$&'()*+,;=~-._")
139
+ candidate = "%s://%s%s" % (scheme, host, encoded)
140
+ if len(candidate) <= MAX_URL_LENGTH:
141
+ page_url = candidate
142
+ origin = None
143
+ if referrer:
144
+ try:
145
+ parts = urlsplit(referrer)
146
+ authority = parts.netloc.rsplit("@", 1)[-1]
147
+ if parts.scheme in ("http", "https") and _valid_authority(authority):
148
+ candidate = "%s://%s" % (parts.scheme, authority)
149
+ if len(candidate) <= MAX_URL_LENGTH:
150
+ origin = candidate
151
+ except ValueError:
152
+ origin = None
153
+ locale = None
154
+ if accept_language:
155
+ first = accept_language.split(",")[0].split(";")[0].strip()
156
+ if len(first) <= MAX_LOCALE_LENGTH and _LOCALE.fullmatch(first):
157
+ locale = first
158
+ if not (page_url or origin or locale):
159
+ return None
160
+ return Context(page_url=page_url, referrer=origin, locale=locale)
161
+
162
+
163
+ def _valid_authority(authority: str) -> bool:
164
+ match = _AUTHORITY.fullmatch(authority)
165
+ if match is None:
166
+ return False
167
+ if match.group("ipv6") is None:
168
+ return True
169
+ try:
170
+ ipaddress.IPv6Address(match.group("ipv6"))
171
+ except ValueError:
172
+ return False
173
+ return True
174
+
175
+
176
+ def resolve_safely(resolver: Any, request: Any) -> Any:
177
+ """Çözümleyici hatası uygulamayı düşürmez; değer yok sayılır (izin için bu 'izin yok' demektir)."""
178
+ if resolver is None:
179
+ return None
180
+ try:
181
+ return resolver(request)
182
+ except Exception as exc: # noqa: BLE001 - uygulama kodu her hatayı atabilir, istek düşmemeli
183
+ _log.warning("feralin: çözümleyici hata verdi: %s", type(exc).__name__)
184
+ return None
185
+
186
+
187
+ def consent_or_none(value: Any) -> Consent:
188
+ return value if isinstance(value, Consent) else Consent()
@@ -0,0 +1,116 @@
1
+ """Saf ASGI ara katmanı: FastAPI ve Starlette ile çalışır, yanıt akışına dokunmaz. Her HTTP isteğine `request.state.feralin`
2
+ ekler. Olay üretimi ağa çıkmaz, arka plan iş parçacığı gönderir. Uygulama kapanırken (lifespan) kuyruk gönderilir.
3
+
4
+ Örnek::
5
+
6
+ app = FastAPI()
7
+ app.add_middleware(
8
+ FeralinMiddleware,
9
+ project_key=os.environ["FERALIN_PROJECT_KEY"], # yalnız pk_ anahtarı
10
+ collect_url="https://collect.example.com",
11
+ resolve_consent=izin_cozumleyici, # Request -> feralin.Consent; sync veya async; yoksa izin yok
12
+ )
13
+
14
+ @app.post("/siparis")
15
+ def siparis(feralin: RequestFeralin = Depends(get_feralin)):
16
+ feralin.track("order_completed", {"order_id": "ord_1"})
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import asyncio
22
+ import inspect
23
+ import logging
24
+ from typing import Any, Callable
25
+
26
+ from feralin import Consent, Context
27
+ from starlette.requests import HTTPConnection, Request
28
+
29
+ from ._core import ConsentClientPool, RequestFeralin, clean_context, consent_or_none, resolve_safely
30
+
31
+ _log = logging.getLogger("feralin")
32
+
33
+ _NOOP = RequestFeralin(pool=None, consent=Consent())
34
+
35
+
36
+ async def _resolve(resolver: Callable[[Any], Any] | None, connection: HTTPConnection) -> Any:
37
+ value = resolve_safely(resolver, connection)
38
+ if inspect.isawaitable(value):
39
+ try:
40
+ return await value
41
+ except Exception as exc: # noqa: BLE001 - uygulama kodu her hatayı atabilir, istek düşmemeli
42
+ _log.warning("feralin: çözümleyici hata verdi: %s", type(exc).__name__)
43
+ return None
44
+ return value
45
+
46
+
47
+ class FeralinMiddleware:
48
+ def __init__(
49
+ self,
50
+ app: Any,
51
+ *,
52
+ project_key: str | None = None,
53
+ collect_url: str | None = None,
54
+ pool: ConsentClientPool | None = None,
55
+ resolve_consent: Callable[[Any], Any] | None = None,
56
+ resolve_user_id: Callable[[Any], Any] | None = None,
57
+ resolve_anonymous_id: Callable[[Any], Any] | None = None,
58
+ resolve_session_id: Callable[[Any], Any] | None = None,
59
+ include_context: bool = True,
60
+ **client_options: Any,
61
+ ) -> None:
62
+ self.app = app
63
+ if pool is None:
64
+ if not project_key or not collect_url:
65
+ raise ValueError("project_key ve collect_url zorunlu (veya pool verin)")
66
+ pool = ConsentClientPool(project_key, collect_url, **client_options)
67
+ self.pool = pool
68
+ self.resolve_consent = resolve_consent
69
+ self.resolve_user_id = resolve_user_id
70
+ self.resolve_anonymous_id = resolve_anonymous_id
71
+ self.resolve_session_id = resolve_session_id
72
+ self.include_context = include_context
73
+
74
+ async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None:
75
+ if scope["type"] == "http":
76
+ scope.setdefault("state", {})["feralin"] = await self._bind(Request(scope))
77
+ elif scope["type"] == "lifespan":
78
+ receive = self._closing_receive(receive)
79
+ await self.app(scope, receive, send)
80
+
81
+ def _closing_receive(self, receive: Any) -> Any:
82
+ async def wrapped() -> Any:
83
+ message = await receive()
84
+ if message.get("type") == "lifespan.shutdown":
85
+ # Ağ çağrısı olay döngüsünü kilitlemesin.
86
+ await asyncio.to_thread(self.pool.close)
87
+ return message
88
+
89
+ return wrapped
90
+
91
+ async def _bind(self, request: Request) -> RequestFeralin:
92
+ consent = consent_or_none(await _resolve(self.resolve_consent, request))
93
+ context = self._context(request) if self.include_context and consent.analytics else None
94
+ return RequestFeralin(
95
+ pool=self.pool,
96
+ consent=consent,
97
+ user_id=await _resolve(self.resolve_user_id, request),
98
+ anonymous_id=await _resolve(self.resolve_anonymous_id, request),
99
+ session_id=await _resolve(self.resolve_session_id, request),
100
+ context=context,
101
+ )
102
+
103
+ @staticmethod
104
+ def _context(request: Request) -> Context | None:
105
+ try:
106
+ url = request.url
107
+ scheme, host, path = url.scheme, url.netloc, url.path
108
+ except ValueError:
109
+ # Starlette adresi Host başlığından kurar; `Host: [x` urlsplit'te hata verir. Bağlam gitmez, istek etkilenmez.
110
+ scheme = host = path = None
111
+ return clean_context(scheme, host, path, request.headers.get("referer"), request.headers.get("accept-language"))
112
+
113
+
114
+ def get_feralin(request: Request) -> RequestFeralin:
115
+ """FastAPI bağımlılığı: `feralin: RequestFeralin = Depends(get_feralin)`. Ara katman yoksa olay üretmeyen yüzey döner."""
116
+ return getattr(request.state, "feralin", _NOOP)
File without changes
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: feralin-fastapi
3
+ Version: 0.1.0
4
+ Summary: Feralin Python SDK için FastAPI ve Starlette ara katmanı: istek başına izin ve kimlik geçirme
5
+ Author: Feralin
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://feralin.com
8
+ Project-URL: Repository, https://github.com/feralincom/sdk
9
+ Project-URL: Documentation, https://github.com/feralincom/sdk/blob/main/docs/sdk/python-fastapi.md
10
+ Project-URL: Changelog, https://github.com/feralincom/sdk/blob/main/sdks/python-fastapi/CHANGELOG.md
11
+ Keywords: analytics,attribution,feralin,fastapi,asgi
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: FastAPI
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: feralin<0.2,>=0.1
21
+ Requires-Dist: starlette>=0.27
22
+ Provides-Extra: fastapi
23
+ Requires-Dist: fastapi>=0.100; extra == "fastapi"
24
+ Dynamic: license-file
25
+
26
+ # feralin-fastapi
27
+
28
+ `feralin` üstünde saf ASGI ara katmanı. FastAPI ve Starlette ile çalışır, yanıt akışına dokunmaz. Her isteğe `request.state.feralin` ekler, uygulama kapanırken kuyruğu gönderir.
29
+
30
+ ## Durum
31
+
32
+ | Konu | Durum |
33
+ |---|---|
34
+ | Birim testleri (FastAPI 0.162, Starlette 1.10, TestClient) | Geçiyor |
35
+ | Temiz kurulum + gerçek `services/collect` | `scripts/sdk-e2e/run.mjs python-fastapi` ile geçti; istekler TestClient'tan girer |
36
+ | Gerçek uvicorn süreci, eski FastAPI sürümleri | Sınanmadı |
37
+ | PyPI yayını | `BLOCKED_EXTERNAL`: hesap yok, `feralin` çekirdeği de yayınlanmadı |
38
+
39
+ ## Kurulum
40
+
41
+ ```bash
42
+ pip install ./sdks/python ./sdks/python-fastapi fastapi
43
+ ```
44
+
45
+ ## Kullanım
46
+
47
+ ```python
48
+ from fastapi import Depends, FastAPI, Request
49
+ from feralin import Consent
50
+ from feralin_fastapi import FeralinMiddleware, RequestFeralin, get_feralin
51
+
52
+ def izin(request: Request) -> Consent:
53
+ return Consent(analytics=request.cookies.get("izin") == "evet")
54
+
55
+ app = FastAPI()
56
+ app.add_middleware(
57
+ FeralinMiddleware,
58
+ project_key=os.environ["FERALIN_PROJECT_KEY"], # yalnız pk_ anahtarı
59
+ collect_url="https://collect.example.com",
60
+ resolve_consent=izin,
61
+ )
62
+
63
+ @app.post("/siparis")
64
+ async def siparis(feralin: RequestFeralin = Depends(get_feralin)):
65
+ feralin.track("order_completed", {"order_id": "ord_1"})
66
+ ```
67
+
68
+ `track` ağa çıkmaz, async rotada güvenlidir. `flush()` ağı bekler; async rotada `await asyncio.to_thread(feralin.flush)` kullanın.
69
+
70
+ ## İzin
71
+
72
+ Çekirdek izni istemci düzeyinde tutar; bu paket izin değeri başına ayrı istemci kullanır (en çok 8 arka plan iş parçacığı). Çözümleyici sync veya async olabilir. Yoksa, hata atarsa veya `Consent` döndürmezse izin yok sayılır, istek düşmez. `fr_click` yalnız `advertising=True` iken gider.
73
+
74
+ ## Veri
75
+
76
+ IP, User-Agent ve çerez okunmaz. `page_url` sorgusuz, `referrer` yalnız origin, `locale` ilk dil etiketidir. Yolda kişisel veri varsa `include_context=False` verin. Geçersiz olay istisna atmaz: `None` döner, uyarı loglanır.
77
+
78
+ ## Desteklenmeyenler
79
+
80
+ WebSocket bağlantılarına yüzey eklenmez. `utm_*` okunmaz. `group`, `set_user_properties`, `track_revenue`, hata raporlama, OTel ve kalıcı kuyruk yoktur. Lifespan çalışmayan sunucuda kapanış gönderimi `atexit` ile denenir.
81
+
82
+ ## Test
83
+
84
+ ```bash
85
+ python -m venv .venv
86
+ .venv/Scripts/python -m pip install fastapi httpx ./sdks/python
87
+ cd sdks/python-fastapi && ../../.venv/Scripts/python -X utf8 -m unittest discover -s tests
88
+ ```
@@ -0,0 +1,9 @@
1
+ feralin_fastapi/__init__.py,sha256=0C48bte_b0amHfk5ysZ-6laUEDdpjI69GQnB77WRQ78,374
2
+ feralin_fastapi/_core.py,sha256=uWu_FK_NCnLPhS2g5MDwzokOPWKNThw8WW4AiFwJjcs,8046
3
+ feralin_fastapi/middleware.py,sha256=L5T9ky22tO3ZSE025ttKMk7N8f0lOwBslAFrJT8BvaI,4754
4
+ feralin_fastapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ feralin_fastapi-0.1.0.dist-info/licenses/LICENSE,sha256=7wcl7cnF93XyawjPQQEPOOLDrq_zXoZ96W2A8LbgaNw,1064
6
+ feralin_fastapi-0.1.0.dist-info/METADATA,sha256=3WikU0KetY9_xf4PleOAyXUqcZ-RqUh_of3Si3rFMO0,3603
7
+ feralin_fastapi-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ feralin_fastapi-0.1.0.dist-info/top_level.txt,sha256=tqhwBKYnaqsiO-HqQhygjBN0KVUZegL8ngQ2mVfn4qg,16
9
+ feralin_fastapi-0.1.0.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Feralin
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
+ feralin_fastapi