feralin-fastapi 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.
- feralin_fastapi-0.1.0/LICENSE +21 -0
- feralin_fastapi-0.1.0/PKG-INFO +88 -0
- feralin_fastapi-0.1.0/README.md +63 -0
- feralin_fastapi-0.1.0/pyproject.toml +38 -0
- feralin_fastapi-0.1.0/setup.cfg +4 -0
- feralin_fastapi-0.1.0/src/feralin_fastapi/__init__.py +8 -0
- feralin_fastapi-0.1.0/src/feralin_fastapi/_core.py +188 -0
- feralin_fastapi-0.1.0/src/feralin_fastapi/middleware.py +116 -0
- feralin_fastapi-0.1.0/src/feralin_fastapi/py.typed +0 -0
- feralin_fastapi-0.1.0/src/feralin_fastapi.egg-info/PKG-INFO +88 -0
- feralin_fastapi-0.1.0/src/feralin_fastapi.egg-info/SOURCES.txt +13 -0
- feralin_fastapi-0.1.0/src/feralin_fastapi.egg-info/dependency_links.txt +1 -0
- feralin_fastapi-0.1.0/src/feralin_fastapi.egg-info/requires.txt +5 -0
- feralin_fastapi-0.1.0/src/feralin_fastapi.egg-info/top_level.txt +1 -0
- feralin_fastapi-0.1.0/tests/test_middleware.py +246 -0
|
@@ -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,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,63 @@
|
|
|
1
|
+
# feralin-fastapi
|
|
2
|
+
|
|
3
|
+
`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.
|
|
4
|
+
|
|
5
|
+
## Durum
|
|
6
|
+
|
|
7
|
+
| Konu | Durum |
|
|
8
|
+
|---|---|
|
|
9
|
+
| Birim testleri (FastAPI 0.162, Starlette 1.10, TestClient) | Geçiyor |
|
|
10
|
+
| Temiz kurulum + gerçek `services/collect` | `scripts/sdk-e2e/run.mjs python-fastapi` ile geçti; istekler TestClient'tan girer |
|
|
11
|
+
| Gerçek uvicorn süreci, eski FastAPI sürümleri | Sınanmadı |
|
|
12
|
+
| PyPI yayını | `BLOCKED_EXTERNAL`: hesap yok, `feralin` çekirdeği de yayınlanmadı |
|
|
13
|
+
|
|
14
|
+
## Kurulum
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install ./sdks/python ./sdks/python-fastapi fastapi
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Kullanım
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from fastapi import Depends, FastAPI, Request
|
|
24
|
+
from feralin import Consent
|
|
25
|
+
from feralin_fastapi import FeralinMiddleware, RequestFeralin, get_feralin
|
|
26
|
+
|
|
27
|
+
def izin(request: Request) -> Consent:
|
|
28
|
+
return Consent(analytics=request.cookies.get("izin") == "evet")
|
|
29
|
+
|
|
30
|
+
app = FastAPI()
|
|
31
|
+
app.add_middleware(
|
|
32
|
+
FeralinMiddleware,
|
|
33
|
+
project_key=os.environ["FERALIN_PROJECT_KEY"], # yalnız pk_ anahtarı
|
|
34
|
+
collect_url="https://collect.example.com",
|
|
35
|
+
resolve_consent=izin,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
@app.post("/siparis")
|
|
39
|
+
async def siparis(feralin: RequestFeralin = Depends(get_feralin)):
|
|
40
|
+
feralin.track("order_completed", {"order_id": "ord_1"})
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`track` ağa çıkmaz, async rotada güvenlidir. `flush()` ağı bekler; async rotada `await asyncio.to_thread(feralin.flush)` kullanın.
|
|
44
|
+
|
|
45
|
+
## İzin
|
|
46
|
+
|
|
47
|
+
Ç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.
|
|
48
|
+
|
|
49
|
+
## Veri
|
|
50
|
+
|
|
51
|
+
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.
|
|
52
|
+
|
|
53
|
+
## Desteklenmeyenler
|
|
54
|
+
|
|
55
|
+
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.
|
|
56
|
+
|
|
57
|
+
## Test
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
python -m venv .venv
|
|
61
|
+
.venv/Scripts/python -m pip install fastapi httpx ./sdks/python
|
|
62
|
+
cd sdks/python-fastapi && ../../.venv/Scripts/python -X utf8 -m unittest discover -s tests
|
|
63
|
+
```
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "feralin-fastapi"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Feralin Python SDK için FastAPI ve Starlette ara katmanı: istek başına izin ve kimlik geçirme"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
# PEP 639 lisans ifadesi (setuptools 77+); lisans sınıflandırıcısıyla birlikte kullanılamaz.
|
|
12
|
+
license = "MIT"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
authors = [{ name = "Feralin" }]
|
|
15
|
+
keywords = ["analytics", "attribution", "feralin", "fastapi", "asgi"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 3 - Alpha",
|
|
18
|
+
"Framework :: FastAPI",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
21
|
+
"Typing :: Typed",
|
|
22
|
+
]
|
|
23
|
+
dependencies = ["feralin>=0.1,<0.2", "starlette>=0.27"]
|
|
24
|
+
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
fastapi = ["fastapi>=0.100"]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://feralin.com"
|
|
30
|
+
Repository = "https://github.com/feralincom/sdk"
|
|
31
|
+
Documentation = "https://github.com/feralincom/sdk/blob/main/docs/sdk/python-fastapi.md"
|
|
32
|
+
Changelog = "https://github.com/feralincom/sdk/blob/main/sdks/python-fastapi/CHANGELOG.md"
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.packages.find]
|
|
35
|
+
where = ["src"]
|
|
36
|
+
|
|
37
|
+
[tool.setuptools.package-data]
|
|
38
|
+
feralin_fastapi = ["py.typed"]
|
|
@@ -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,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/feralin_fastapi/__init__.py
|
|
5
|
+
src/feralin_fastapi/_core.py
|
|
6
|
+
src/feralin_fastapi/middleware.py
|
|
7
|
+
src/feralin_fastapi/py.typed
|
|
8
|
+
src/feralin_fastapi.egg-info/PKG-INFO
|
|
9
|
+
src/feralin_fastapi.egg-info/SOURCES.txt
|
|
10
|
+
src/feralin_fastapi.egg-info/dependency_links.txt
|
|
11
|
+
src/feralin_fastapi.egg-info/requires.txt
|
|
12
|
+
src/feralin_fastapi.egg-info/top_level.txt
|
|
13
|
+
tests/test_middleware.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
feralin_fastapi
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Gerçek FastAPI uygulaması ve TestClient; yalnız çekirdeğin transport'u enjekte edilir."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import pathlib
|
|
7
|
+
import re
|
|
8
|
+
import sys
|
|
9
|
+
import unittest
|
|
10
|
+
from types import SimpleNamespace
|
|
11
|
+
|
|
12
|
+
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
|
13
|
+
for path in (ROOT / "src", ROOT.parent / "python" / "src"):
|
|
14
|
+
if str(path) not in sys.path:
|
|
15
|
+
sys.path.insert(0, str(path))
|
|
16
|
+
|
|
17
|
+
from fastapi import Depends, FastAPI, Request # noqa: E402
|
|
18
|
+
from fastapi.testclient import TestClient # noqa: E402
|
|
19
|
+
from feralin import ConfigurationError, Consent, TemporaryError # noqa: E402
|
|
20
|
+
from feralin_fastapi import ConsentClientPool, FeralinMiddleware, RequestFeralin, clean_context, get_feralin # noqa: E402
|
|
21
|
+
|
|
22
|
+
KEY = "pk_test_fastapi_unit_001"
|
|
23
|
+
COLLECT = "http://collector.test"
|
|
24
|
+
|
|
25
|
+
# Kanonik şema; bağlam alanları toplayıcıdaki sınırlarla aynı yerden okunur.
|
|
26
|
+
CONTEXT_SCHEMA = json.loads((ROOT.parents[1] / "packages/schemas/utp/v1/event.schema.json").read_text(encoding="utf-8"))["properties"]["context"]["properties"]
|
|
27
|
+
# Toplayıcının `format: uri` denetimi Go net/url.Parse'tır; bu desen onun kabul ettiklerinin dar alt kümesidir.
|
|
28
|
+
PAGE_URL = re.compile(r"^https?://[A-Za-z0-9._~-]+(:[0-9]+)?(/([A-Za-z0-9._~!$&'()*+,;=:@/-]|%[0-9A-Fa-f]{2})*)?$")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def assert_schema_context(case, context):
|
|
32
|
+
"""Bağlam şemadan geçmeli: tek geçersiz alan toplayıcıda tüm batch'i 400 ile düşürür."""
|
|
33
|
+
for field, value in context.items():
|
|
34
|
+
case.assertIn(field, CONTEXT_SCHEMA)
|
|
35
|
+
case.assertLessEqual(len(value), CONTEXT_SCHEMA[field]["maxLength"], field)
|
|
36
|
+
if "page_url" in context:
|
|
37
|
+
case.assertRegex(context["page_url"], PAGE_URL)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Transport:
|
|
42
|
+
def __init__(self, responses=None):
|
|
43
|
+
self.calls = []
|
|
44
|
+
self.responses = list(responses or [])
|
|
45
|
+
|
|
46
|
+
def __call__(self, url, data, headers, timeout):
|
|
47
|
+
self.calls.append({"url": url, "headers": headers, "events": json.loads(data)["events"]})
|
|
48
|
+
response = self.responses.pop(0) if self.responses else None
|
|
49
|
+
if isinstance(response, Exception):
|
|
50
|
+
raise response
|
|
51
|
+
if response is not None:
|
|
52
|
+
return response
|
|
53
|
+
return 202, json.dumps({"batch_id": "b%d" % len(self.calls), "accepted": len(self.calls[-1]["events"]), "rejected": 0}).encode(), {}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def consent_from_header(request: Request) -> Consent:
|
|
57
|
+
return Consent(analytics=request.headers.get("x-izin") == "evet", advertising=request.headers.get("x-reklam") == "evet")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def make_app(transport, **options):
|
|
61
|
+
app = FastAPI()
|
|
62
|
+
options.setdefault("resolve_consent", consent_from_header)
|
|
63
|
+
app.add_middleware(FeralinMiddleware, project_key=KEY, collect_url=COLLECT, flush_interval=0, transport=transport, **options)
|
|
64
|
+
|
|
65
|
+
@app.get("/sync/{order_id}")
|
|
66
|
+
def sync_route(order_id: str, feralin: RequestFeralin = Depends(get_feralin)):
|
|
67
|
+
return {"event": feralin.track("order_completed", {"order_id": order_id, "fr_click": "clk_1"})}
|
|
68
|
+
|
|
69
|
+
@app.get("/async/{order_id}")
|
|
70
|
+
async def async_route(order_id: str, feralin: RequestFeralin = Depends(get_feralin)):
|
|
71
|
+
return {"event": feralin.track("order_completed", {"order_id": order_id})}
|
|
72
|
+
|
|
73
|
+
@app.get("/durum")
|
|
74
|
+
def state_route(request: Request):
|
|
75
|
+
return {"analytics": request.state.feralin.consent.analytics}
|
|
76
|
+
|
|
77
|
+
@app.get("/gecersiz")
|
|
78
|
+
def invalid_route(feralin: RequestFeralin = Depends(get_feralin)):
|
|
79
|
+
return {"event": feralin.track("Bad-Name")}
|
|
80
|
+
|
|
81
|
+
return app
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class MiddlewareTests(unittest.TestCase):
|
|
85
|
+
def test_izin_yokken_olay_uretilmez_istek_basarili(self):
|
|
86
|
+
transport = Transport()
|
|
87
|
+
with TestClient(make_app(transport)) as client:
|
|
88
|
+
response = client.get("/sync/1")
|
|
89
|
+
self.assertEqual(response.status_code, 200)
|
|
90
|
+
self.assertIsNone(response.json()["event"])
|
|
91
|
+
self.assertEqual(transport.calls, [])
|
|
92
|
+
|
|
93
|
+
def test_istek_basina_izin_ayri_gider_kapanista_gonderilir(self):
|
|
94
|
+
transport = Transport()
|
|
95
|
+
with TestClient(make_app(transport, resolve_user_id=lambda request: request.headers.get("x-kullanici"))) as client:
|
|
96
|
+
reklamli = client.get("/sync/1?token=GIZLI", headers={"x-izin": "evet", "x-reklam": "evet", "x-kullanici": "user_42", "referer": "https://ref.example.test/a?b=GIZLI", "accept-language": "tr-TR,tr;q=0.9"}).json()["event"]
|
|
97
|
+
reklamsiz = client.get("/sync/2", headers={"x-izin": "evet"}).json()["event"]
|
|
98
|
+
self.assertIsNone(client.get("/sync/3").json()["event"])
|
|
99
|
+
self.assertEqual(transport.calls, [])
|
|
100
|
+
self.assertEqual(reklamli["properties"]["fr_click"], "clk_1")
|
|
101
|
+
self.assertEqual(reklamli["user_id"], "user_42")
|
|
102
|
+
self.assertNotIn("fr_click", reklamsiz["properties"])
|
|
103
|
+
self.assertNotIn("user_id", reklamsiz)
|
|
104
|
+
self.assertEqual(len(transport.calls), 2)
|
|
105
|
+
self.assertEqual(transport.calls[0]["url"], "http://collector.test/v1/batch")
|
|
106
|
+
self.assertEqual(transport.calls[0]["headers"]["X-Feralin-Project-Key"], KEY)
|
|
107
|
+
raw = json.dumps(transport.calls)
|
|
108
|
+
self.assertNotIn("GIZLI", raw)
|
|
109
|
+
self.assertNotIn("verified", raw)
|
|
110
|
+
context = reklamli["context"]
|
|
111
|
+
self.assertEqual(context["page_url"], "http://testserver/sync/1")
|
|
112
|
+
self.assertEqual(context["referrer"], "https://ref.example.test")
|
|
113
|
+
self.assertEqual(context["locale"], "tr-TR")
|
|
114
|
+
|
|
115
|
+
def test_async_cozumleyici_ve_async_rota(self):
|
|
116
|
+
async def resolver(request):
|
|
117
|
+
return Consent(analytics=True)
|
|
118
|
+
|
|
119
|
+
with TestClient(make_app(Transport(), resolve_consent=resolver)) as client:
|
|
120
|
+
self.assertIsNotNone(client.get("/async/1").json()["event"])
|
|
121
|
+
self.assertEqual(client.get("/durum").json(), {"analytics": True})
|
|
122
|
+
|
|
123
|
+
def test_cozumleyici_hatasi_izin_yok_sayilir(self):
|
|
124
|
+
def broken(request):
|
|
125
|
+
raise RuntimeError("CMP yok")
|
|
126
|
+
|
|
127
|
+
async def broken_async(request):
|
|
128
|
+
raise RuntimeError("CMP yok")
|
|
129
|
+
|
|
130
|
+
for resolver in (broken, broken_async):
|
|
131
|
+
with TestClient(make_app(Transport(), resolve_consent=resolver)) as client:
|
|
132
|
+
with self.assertLogs("feralin", level="WARNING"):
|
|
133
|
+
response = client.get("/sync/1")
|
|
134
|
+
self.assertEqual(response.status_code, 200)
|
|
135
|
+
self.assertIsNone(response.json()["event"])
|
|
136
|
+
|
|
137
|
+
def test_gecersiz_olay_uygulamayi_dusurmez(self):
|
|
138
|
+
with TestClient(make_app(Transport())) as client:
|
|
139
|
+
with self.assertLogs("feralin", level="WARNING"):
|
|
140
|
+
response = client.get("/gecersiz", headers={"x-izin": "evet"})
|
|
141
|
+
self.assertEqual(response.status_code, 200)
|
|
142
|
+
self.assertIsNone(response.json()["event"])
|
|
143
|
+
|
|
144
|
+
def test_baglam_kapatilabilir(self):
|
|
145
|
+
with TestClient(make_app(Transport(), include_context=False)) as client:
|
|
146
|
+
event = client.get("/sync/1", headers={"x-izin": "evet"}).json()["event"]
|
|
147
|
+
self.assertNotIn("context", event)
|
|
148
|
+
|
|
149
|
+
def test_saldirgan_baslik_batch_dusurmez_istek_etkilenmez(self):
|
|
150
|
+
with TestClient(make_app(Transport())) as client:
|
|
151
|
+
uzun = client.get("/sync/1", headers={"x-izin": "evet", "referer": "https://" + "r" * 3000 + ".example.test/"})
|
|
152
|
+
self.assertEqual(uzun.status_code, 200)
|
|
153
|
+
self.assertNotIn("referrer", uzun.json()["event"]["context"])
|
|
154
|
+
assert_schema_context(self, uzun.json()["event"]["context"])
|
|
155
|
+
# Güncel Starlette geçersiz Host yerine sunucu adresini kullanır; sonuç her durumda şemadan geçmeli.
|
|
156
|
+
for host in ("a b", "a<b>", "h:port", "[bad"):
|
|
157
|
+
response = client.get("/sync/2", headers={"x-izin": "evet", "host": host})
|
|
158
|
+
self.assertEqual(response.status_code, 200, host)
|
|
159
|
+
assert_schema_context(self, response.json()["event"].get("context", {}))
|
|
160
|
+
yuzde = client.get("/sync/yuzde%25", headers={"x-izin": "evet"})
|
|
161
|
+
self.assertEqual(yuzde.json()["event"]["context"]["page_url"], "http://testserver/sync/yuzde%25")
|
|
162
|
+
|
|
163
|
+
def test_eski_starlette_ham_host_ile_baglam_gitmez(self):
|
|
164
|
+
# fastapi>=0.100 aralığındaki eski Starlette adresi Host başlığından doğrudan kurar.
|
|
165
|
+
class Patlayan:
|
|
166
|
+
headers = {}
|
|
167
|
+
|
|
168
|
+
@property
|
|
169
|
+
def url(self):
|
|
170
|
+
raise ValueError("Invalid IPv6 URL")
|
|
171
|
+
|
|
172
|
+
self.assertIsNone(FeralinMiddleware._context(Patlayan()))
|
|
173
|
+
ham = SimpleNamespace(headers={}, url=SimpleNamespace(scheme="http", netloc="a b", path="/x"))
|
|
174
|
+
self.assertIsNone(FeralinMiddleware._context(ham))
|
|
175
|
+
|
|
176
|
+
def test_ara_katman_yoksa_bagimlilik_olay_uretmez(self):
|
|
177
|
+
app = FastAPI()
|
|
178
|
+
|
|
179
|
+
@app.get("/")
|
|
180
|
+
def route(feralin: RequestFeralin = Depends(get_feralin)):
|
|
181
|
+
return {"event": feralin.track("x_event"), "sent": feralin.flush().sent}
|
|
182
|
+
|
|
183
|
+
self.assertEqual(TestClient(app).get("/").json(), {"event": None, "sent": 0})
|
|
184
|
+
|
|
185
|
+
def test_gizli_anahtar_ve_eksik_ayar_acilista_reddedilir(self):
|
|
186
|
+
with self.assertRaises(ConfigurationError):
|
|
187
|
+
FeralinMiddleware(None, project_key="sk_live_gizli_0001", collect_url=COLLECT)
|
|
188
|
+
with self.assertRaises(ValueError):
|
|
189
|
+
FeralinMiddleware(None)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class PoolTests(unittest.TestCase):
|
|
193
|
+
def test_401_kuyrugu_atar_ag_hatasi_tutar_ayni_anahtarla_dener(self):
|
|
194
|
+
rejected = Transport([(401, b'{"title":"bad key"}', {})])
|
|
195
|
+
pool = ConsentClientPool(KEY, COLLECT, flush_interval=0, transport=rejected)
|
|
196
|
+
pool.track(Consent(analytics=True), "order_completed")
|
|
197
|
+
result = pool.flush()
|
|
198
|
+
self.assertEqual([result.status, result.rejected, result.retained], [401, 1, 0])
|
|
199
|
+
pool.close()
|
|
200
|
+
|
|
201
|
+
flaky = Transport([TemporaryError("ağ yok", status=0)])
|
|
202
|
+
pool = ConsentClientPool(KEY, COLLECT, flush_interval=0, transport=flaky)
|
|
203
|
+
pool.track(Consent(analytics=True), "order_completed")
|
|
204
|
+
lost = pool.flush()
|
|
205
|
+
self.assertEqual([lost.status, lost.retained], [0, 1])
|
|
206
|
+
pool.track(Consent(analytics=True), "order_shipped")
|
|
207
|
+
self.assertEqual(pool.flush().status, 202)
|
|
208
|
+
keys = [call["headers"]["Idempotency-Key"] for call in flaky.calls]
|
|
209
|
+
self.assertEqual(keys[0], keys[1])
|
|
210
|
+
pool.close()
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
class ContextTests(unittest.TestCase):
|
|
214
|
+
def test_gecersiz_alanlar_gonderilmez(self):
|
|
215
|
+
self.assertIsNone(clean_context("ftp", "h", "/", None, None))
|
|
216
|
+
self.assertIsNone(clean_context(None, None, None, "javascript:alert(1)", "*"))
|
|
217
|
+
context = clean_context("https", "h.example.test", "/ç a", "https://u:p@ref.example.test/x", "en")
|
|
218
|
+
self.assertEqual(context.page_url, "https://h.example.test/%C3%A7%20a")
|
|
219
|
+
self.assertEqual(context.referrer, "https://ref.example.test")
|
|
220
|
+
|
|
221
|
+
def test_saldirgan_baglami_semadan_gecer(self):
|
|
222
|
+
uzun_referrer = "https://" + "r" * 3000 + ".example.test/x"
|
|
223
|
+
context = clean_context("https", "h.example.test", "/x", uzun_referrer, "tr")
|
|
224
|
+
self.assertIsNone(context.referrer)
|
|
225
|
+
self.assertEqual(context.page_url, "https://h.example.test/x")
|
|
226
|
+
assert_schema_context(self, context.to_dict())
|
|
227
|
+
for host in ("a b", "a<b>", "h:port", "h:80:90", "[::1", "[zz::1]", "hést", "a%zz", 'a"b'):
|
|
228
|
+
self.assertIsNone(clean_context("http", host, "/x", None, None), host)
|
|
229
|
+
self.assertIsNone(clean_context(None, None, None, "http://%s/x" % host, None), host)
|
|
230
|
+
self.assertEqual(clean_context("http", "[::1]:8080", "/x", None, None).page_url, "http://[::1]:8080/x")
|
|
231
|
+
self.assertEqual(clean_context(None, None, None, "https://[::1]/x", None).referrer, "https://[::1]")
|
|
232
|
+
self.assertEqual(clean_context("http", "h:8080", "/100%", None, None).page_url, "http://h:8080/100%25")
|
|
233
|
+
self.assertEqual(clean_context("http", "h", "/a%20b", None, None).page_url, "http://h/a%20b")
|
|
234
|
+
self.assertIsNone(clean_context(None, None, None, None, "tr\u0000x"))
|
|
235
|
+
self.assertIsNone(clean_context(None, None, None, None, "t r"))
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
class SharedCoreTests(unittest.TestCase):
|
|
239
|
+
def test_ortak_katman_django_ile_ayni(self):
|
|
240
|
+
here = (ROOT / "src" / "feralin_fastapi" / "_core.py").read_bytes()
|
|
241
|
+
other = (ROOT.parent / "python-django" / "src" / "feralin_django" / "_core.py").read_bytes()
|
|
242
|
+
self.assertEqual(here, other)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
if __name__ == "__main__":
|
|
246
|
+
unittest.main()
|