simple-module-analytics 0.0.15__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.
- simple_module_analytics-0.0.15.dist-info/METADATA +57 -0
- simple_module_analytics-0.0.15.dist-info/RECORD +50 -0
- simple_module_analytics-0.0.15.dist-info/WHEEL +4 -0
- simple_module_analytics-0.0.15.dist-info/entry_points.txt +2 -0
- sm_analytics/__init__.py +1 -0
- sm_analytics/collection/__init__.py +1 -0
- sm_analytics/collection/privacy.py +85 -0
- sm_analytics/collection/retention.py +33 -0
- sm_analytics/collection/service.py +105 -0
- sm_analytics/core/__init__.py +1 -0
- sm_analytics/core/constants.py +15 -0
- sm_analytics/core/geo.py +133 -0
- sm_analytics/core/runtime.py +58 -0
- sm_analytics/core/settings.py +22 -0
- sm_analytics/core/tenancy.py +26 -0
- sm_analytics/index.ts +3 -0
- sm_analytics/locales/de.json +118 -0
- sm_analytics/locales/en.json +118 -0
- sm_analytics/models/__init__.py +87 -0
- sm_analytics/module.py +103 -0
- sm_analytics/package.json +21 -0
- sm_analytics/pages/Dashboard.tsx +164 -0
- sm_analytics/reporting/__init__.py +1 -0
- sm_analytics/reporting/reports.py +145 -0
- sm_analytics/ui/components/DateRangeControl.tsx +126 -0
- sm_analytics/ui/components/DeleteProperty.tsx +68 -0
- sm_analytics/ui/components/FilterChips.tsx +74 -0
- sm_analytics/ui/components/PropertyEditor.tsx +189 -0
- sm_analytics/ui/components/PropertySettings.tsx +120 -0
- sm_analytics/ui/components/RankingPanel.tsx +119 -0
- sm_analytics/ui/components/RecentActivity.tsx +63 -0
- sm_analytics/ui/components/ReportExport.tsx +63 -0
- sm_analytics/ui/components/ReportFilters.tsx +119 -0
- sm_analytics/ui/components/ReportView.tsx +86 -0
- sm_analytics/ui/components/TrafficChart.tsx +123 -0
- sm_analytics/ui/utils/api.ts +52 -0
- sm_analytics/ui/utils/csrf.ts +46 -0
- sm_analytics/ui/utils/hostTracker.ts +52 -0
- sm_analytics/ui/utils/i18n.ts +89 -0
- sm_analytics/ui/utils/reportExport.ts +48 -0
- sm_analytics/ui/utils/tracker.ts +102 -0
- sm_analytics/ui/utils/trackingPaths.ts +36 -0
- sm_analytics/ui/utils/types.ts +55 -0
- sm_analytics/ui/utils/useAnalytics.ts +111 -0
- sm_analytics/web/__init__.py +1 -0
- sm_analytics/web/deps.py +30 -0
- sm_analytics/web/endpoints/__init__.py +1 -0
- sm_analytics/web/endpoints/admin.py +115 -0
- sm_analytics/web/endpoints/public.py +76 -0
- sm_analytics/web/schemas.py +132 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: simple_module_analytics
|
|
3
|
+
Version: 0.0.15
|
|
4
|
+
Summary: Anonymous tenant-scoped web and application analytics with local GeoIP
|
|
5
|
+
Project-URL: Repository, https://github.com/antosubash/simple_module_python_modules
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: analytics,geoip,simple-module,web-analytics
|
|
8
|
+
Requires-Python: >=3.12
|
|
9
|
+
Requires-Dist: pydantic-settings>=2.0
|
|
10
|
+
Requires-Dist: simple-module-core<0.1,>=0.0.44
|
|
11
|
+
Requires-Dist: simple-module-db<0.1,>=0.0.44
|
|
12
|
+
Requires-Dist: simple-module-hosting<0.1,>=0.0.44
|
|
13
|
+
Requires-Dist: simple-module-inertia<0.1,>=0.0.44
|
|
14
|
+
Requires-Dist: simple-module-settings<0.1,>=0.0.44
|
|
15
|
+
Provides-Extra: dev
|
|
16
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
|
|
17
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
18
|
+
Requires-Dist: simple-module-test<0.1,>=0.0.44; extra == 'dev'
|
|
19
|
+
Provides-Extra: geoip
|
|
20
|
+
Requires-Dist: geoip2<6,>=5.2; extra == 'geoip'
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# SimpleModule Analytics
|
|
24
|
+
|
|
25
|
+
Native, tenant-scoped traffic and anonymous application events for SimpleModule
|
|
26
|
+
hosts. Includes a dashboard, daily visitor estimates, sessions, custom events,
|
|
27
|
+
referrers, campaign and device breakdowns, and optional local country/region/city
|
|
28
|
+
geolocation. Public and application tracking are separate opt-ins.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
pip install 'simple_module_analytics[geoip]'
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Install the package in your host and generate/apply that host's Alembic migration.
|
|
37
|
+
The base package also works without the GeoIP extra. For location reporting,
|
|
38
|
+
provision a GeoLite2 City MMDB file separately and configure its absolute path in
|
|
39
|
+
the database-backed Analytics settings. No IP lookup service is called.
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
Open **Analytics**, create a property, enter the exact site origin and allowed
|
|
44
|
+
route patterns, and enable tracking. New properties start paused. Application
|
|
45
|
+
routes such as `/records/:id` store the pattern instead of the record identifier.
|
|
46
|
+
The demo host includes the Inertia adapter; other hosts can use the exported
|
|
47
|
+
`startHostAnalytics`, `initAnalytics`, and `track` frontend functions.
|
|
48
|
+
|
|
49
|
+
No cookies, persistent browser identifiers, raw IP addresses or device coordinates
|
|
50
|
+
are stored. Do Not Track and Global Privacy Control are honored. Location and
|
|
51
|
+
visitor identity are estimates. Reports are tenant-restricted and require
|
|
52
|
+
`analytics.view`; property changes require `analytics.manage`. Retention defaults
|
|
53
|
+
to 90 days. Long-range reports scan raw events, so benchmark your deployment
|
|
54
|
+
before relying on interactive performance at high traffic volumes.
|
|
55
|
+
|
|
56
|
+
See [the guide](docs/index.md) for setup, custom events, metrics, privacy,
|
|
57
|
+
geolocation provisioning, retention operations and verification.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
sm_analytics/__init__.py,sha256=5g9A4nVHbX_LeJ52rTUXlcbzBwwfFk2RHESEmjcKve0,63
|
|
2
|
+
sm_analytics/index.ts,sha256=oCqoaeMNLHW3u8ZrCgg5cdBZBeSBpjAEMFomdprpGrk,205
|
|
3
|
+
sm_analytics/module.py,sha256=YMFZDQv-1Pj-fw-DTJrGGOKDTOm9cYwhon9uqonRMHs,4238
|
|
4
|
+
sm_analytics/collection/__init__.py,sha256=w5LLMZthZXl_YdTKkq4Kkp0DWV2SVhDdYmFRvONLW74,26
|
|
5
|
+
sm_analytics/collection/privacy.py,sha256=8wWb6gOMAkvNqMqTU-eXKrr4Hey7Z0OWwRYNVhqxGwM,2559
|
|
6
|
+
sm_analytics/collection/retention.py,sha256=20bAqAl2TiSvq1KaBLtzc2kyMtRA7UyGQTAVnDX5OY8,1038
|
|
7
|
+
sm_analytics/collection/service.py,sha256=2v8kX1Wor8idU9NNMX0XgWKMmmS16WATUskpXRjIBW8,3512
|
|
8
|
+
sm_analytics/core/__init__.py,sha256=w5LLMZthZXl_YdTKkq4Kkp0DWV2SVhDdYmFRvONLW74,26
|
|
9
|
+
sm_analytics/core/constants.py,sha256=1wZHR-gBiNgKLX3FpcxEype8Iki0kd2b5sg3rbrSb4E,588
|
|
10
|
+
sm_analytics/core/geo.py,sha256=SJ-eIjeASu2aIPzCWdKakyjTMTJIFzuRhJyFgN2Iw00,4432
|
|
11
|
+
sm_analytics/core/runtime.py,sha256=GPwWDI62RZyvPPC_BTpVQnbBTOQ84MBOp3bxXNcfSPQ,1919
|
|
12
|
+
sm_analytics/core/settings.py,sha256=mCSUk3DZilXuAMr_n5ZjnfzMK7mJa5Dw2WtItqvGhXk,1000
|
|
13
|
+
sm_analytics/core/tenancy.py,sha256=Ga58g4lO-r4I2YsOL994r25bapwgR_LpjDE02ahB82Q,997
|
|
14
|
+
sm_analytics/locales/de.json,sha256=eYfgIHxrBS1qaAq7R3s9sp-yoxllc3bmunpZXRa7bCA,5219
|
|
15
|
+
sm_analytics/locales/en.json,sha256=h1wbqFK-3qA_hc34i7WQA0KtzhiFDfEnDpx-ndkv6W8,4745
|
|
16
|
+
sm_analytics/models/__init__.py,sha256=JFij6R6um0Arppovssts9Wtpzk2s0xstOsAdIDOClFc,3825
|
|
17
|
+
sm_analytics/pages/Dashboard.tsx,sha256=Fv5wyQHTfefA8Eg7Mz8a3_NqA9BlsxH3tp7M3buhatQ,6522
|
|
18
|
+
sm_analytics/reporting/__init__.py,sha256=w5LLMZthZXl_YdTKkq4Kkp0DWV2SVhDdYmFRvONLW74,26
|
|
19
|
+
sm_analytics/reporting/reports.py,sha256=zm_byVvt5cQJyvGNBidH-iUf80bM1AJt2RL-b1xIVZM,4934
|
|
20
|
+
sm_analytics/ui/components/DateRangeControl.tsx,sha256=iFwTAKQoBxrYx_YbtOGYdCt5yiE9vXTlfB1t5b2tPaA,4242
|
|
21
|
+
sm_analytics/ui/components/DeleteProperty.tsx,sha256=AURIEtDVljWq_RTOdg7ke9uptbcVzVhB__gIKTVL3No,2151
|
|
22
|
+
sm_analytics/ui/components/FilterChips.tsx,sha256=mdb97GOF9YbbZYUf45B2PJKrKVQQyXSTJrtWMwC9k5I,2356
|
|
23
|
+
sm_analytics/ui/components/PropertyEditor.tsx,sha256=3R1azh_4Ke43HqO2s1tW0Dx-MW5YFZj_IYN5f_IfKY0,7091
|
|
24
|
+
sm_analytics/ui/components/PropertySettings.tsx,sha256=Gqk_ZNB-DGGPRs_-UAG3d9fJ4z4QmG9U3chgdW3jLrM,4000
|
|
25
|
+
sm_analytics/ui/components/RankingPanel.tsx,sha256=JIDMJp-F-YFuF6pEe33aVWXYEgM1-ThPG_Ur5G4LmRk,4910
|
|
26
|
+
sm_analytics/ui/components/RecentActivity.tsx,sha256=wm3_c2LbHldcbwHDay9fGVvJGK_ISjczZvWy7VsKhGY,2665
|
|
27
|
+
sm_analytics/ui/components/ReportExport.tsx,sha256=424skAQMQN0mquXpoQIwgxZiVUuJS9yfDV2MsxIt0c0,1674
|
|
28
|
+
sm_analytics/ui/components/ReportFilters.tsx,sha256=waIVsRkI3615YdaB-hQ7DpcuYU66Srsodo9T4vA_mJM,4234
|
|
29
|
+
sm_analytics/ui/components/ReportView.tsx,sha256=Tkj9b5-MdNBDxBiV4HWytI36JGZOV1xzQr9ftGqCjIQ,2986
|
|
30
|
+
sm_analytics/ui/components/TrafficChart.tsx,sha256=tngp9ZRGAvbQ1X8D3SfOf0Xlyqcy8VgU4x8cMCDc3HA,4473
|
|
31
|
+
sm_analytics/ui/utils/api.ts,sha256=_NP2RYwK4p-rAcjbphr1iO5TslTOYwGkn5RWJpLWRCI,1958
|
|
32
|
+
sm_analytics/ui/utils/csrf.ts,sha256=QuMzgqmwwWD5VaivWSkLLy30mBrTi3B5HNJqTOfN18w,1619
|
|
33
|
+
sm_analytics/ui/utils/hostTracker.ts,sha256=dgR1RPhA3WqPS63y5NcjpKAc2twJJeX_GZM99oaDvR0,1767
|
|
34
|
+
sm_analytics/ui/utils/i18n.ts,sha256=LDId4Pgalhlf2do6jEchTapg1FsqUA4WZME9eVa9AeY,3005
|
|
35
|
+
sm_analytics/ui/utils/reportExport.ts,sha256=XNOD6kR_Ec2sgWimdNeqFw8zF_Wq-3L0J2FgWEbGdlQ,1936
|
|
36
|
+
sm_analytics/ui/utils/tracker.ts,sha256=ZdLRz7u01acKqOV5KGmNzavNM1qrJuP0sOg8uRtg7hQ,3424
|
|
37
|
+
sm_analytics/ui/utils/trackingPaths.ts,sha256=vHiHwDzdjNFDS45vkwZJ6Wm5hqZcjDybi_a_N97moR8,1021
|
|
38
|
+
sm_analytics/ui/utils/types.ts,sha256=hB-GyevHPT-Zd_bxFCdQ7IcxDBmQkDm4JrtyVkcEaLA,1357
|
|
39
|
+
sm_analytics/ui/utils/useAnalytics.ts,sha256=oIqR5ICRdySrvvteNnluqLBN-3njt9A3y5UD7PdA7c0,3509
|
|
40
|
+
sm_analytics/web/__init__.py,sha256=w5LLMZthZXl_YdTKkq4Kkp0DWV2SVhDdYmFRvONLW74,26
|
|
41
|
+
sm_analytics/web/deps.py,sha256=TQUozRHPY_x2SujuBWV3yYhh53Z8aR_CEKeoXLEpNgM,864
|
|
42
|
+
sm_analytics/web/schemas.py,sha256=mzqGKahwHTqLImwCQdkLmwRM74LNpC_fIfYVxM_YkYw,4716
|
|
43
|
+
sm_analytics/web/endpoints/__init__.py,sha256=w5LLMZthZXl_YdTKkq4Kkp0DWV2SVhDdYmFRvONLW74,26
|
|
44
|
+
sm_analytics/web/endpoints/admin.py,sha256=GliRSkMmJ_y0dV78R2HBB2oZVj4paxH78hU2QwiRUJk,4398
|
|
45
|
+
sm_analytics/web/endpoints/public.py,sha256=i7ER6ofx6gNoGuVXpfKV6PY_6fkldW3cIhkT1rwLc80,2704
|
|
46
|
+
sm_analytics/package.json,sha256=r22Up_qHUUD0JYWusqEAzHCHzUfgdJBK13QhHNdiELU,511
|
|
47
|
+
simple_module_analytics-0.0.15.dist-info/METADATA,sha256=llY55fRjAHDMALHzpjg78bza1CAXvm_BFY4QRnflW6A,2620
|
|
48
|
+
simple_module_analytics-0.0.15.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
49
|
+
simple_module_analytics-0.0.15.dist-info/entry_points.txt,sha256=nZBazPF7IqhyhJiLKTsZpYkghoQH6xbwfDNc7OKxw6I,64
|
|
50
|
+
simple_module_analytics-0.0.15.dist-info/RECORD,,
|
sm_analytics/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Tenant-scoped, anonymous web analytics for SimpleModule."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Analytics services."""
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Reduce request metadata before anything reaches storage."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from urllib.parse import unquote, urlsplit
|
|
11
|
+
|
|
12
|
+
from sm_analytics.core.constants import EXCLUDED_SEGMENTS
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def canonical_path(path: str, patterns: list[str], kind: str) -> str | None:
|
|
16
|
+
if not path.startswith("/") or path.startswith("//") or "\\" in path:
|
|
17
|
+
return None
|
|
18
|
+
clean = urlsplit(path).path
|
|
19
|
+
decoded = unquote(clean).lower()
|
|
20
|
+
if any(s in EXCLUDED_SEGMENTS or s in {".", ".."} for s in decoded.split("/")):
|
|
21
|
+
return None
|
|
22
|
+
if any(ord(c) < 32 for c in decoded) or "\\" in decoded or len(clean) > 500:
|
|
23
|
+
return None
|
|
24
|
+
for pattern in patterns:
|
|
25
|
+
regex = "/".join("[^/]+" if s.startswith(":") else re.escape(s) for s in pattern.split("/"))
|
|
26
|
+
if re.fullmatch(regex, clean):
|
|
27
|
+
return pattern if kind == "application" else clean
|
|
28
|
+
return None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def visitor_key(
|
|
32
|
+
secret: str, tenant: str, property_id: str, ip: str, browser: str, now: datetime
|
|
33
|
+
) -> str:
|
|
34
|
+
if not secret:
|
|
35
|
+
raise ValueError("Analytics requires a provisioned host secret")
|
|
36
|
+
message = json.dumps([tenant, property_id, now.date().isoformat(), ip, browser])
|
|
37
|
+
return hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def user_agent(value: str) -> tuple[str, str, str]:
|
|
41
|
+
value = value.lower()
|
|
42
|
+
browser = next(
|
|
43
|
+
(
|
|
44
|
+
name
|
|
45
|
+
for token, name in [
|
|
46
|
+
("edg/", "Edge"),
|
|
47
|
+
("firefox/", "Firefox"),
|
|
48
|
+
("chrome/", "Chrome"),
|
|
49
|
+
("safari/", "Safari"),
|
|
50
|
+
]
|
|
51
|
+
if token in value
|
|
52
|
+
),
|
|
53
|
+
"Other",
|
|
54
|
+
)
|
|
55
|
+
os = next(
|
|
56
|
+
(
|
|
57
|
+
name
|
|
58
|
+
for token, name in [
|
|
59
|
+
("android", "Android"),
|
|
60
|
+
("iphone", "iOS"),
|
|
61
|
+
("ipad", "iOS"),
|
|
62
|
+
("windows", "Windows"),
|
|
63
|
+
("mac os", "macOS"),
|
|
64
|
+
("linux", "Linux"),
|
|
65
|
+
]
|
|
66
|
+
if token in value
|
|
67
|
+
),
|
|
68
|
+
"Other",
|
|
69
|
+
)
|
|
70
|
+
device = (
|
|
71
|
+
"tablet"
|
|
72
|
+
if "ipad" in value or "tablet" in value
|
|
73
|
+
else "mobile"
|
|
74
|
+
if "mobile" in value
|
|
75
|
+
else "desktop"
|
|
76
|
+
)
|
|
77
|
+
return browser, os, device
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def referrer_host(value: str) -> str:
|
|
81
|
+
try:
|
|
82
|
+
parts = urlsplit(value if "://" in value else f"https://{value}")
|
|
83
|
+
return (parts.hostname or "")[:253] if parts.scheme in {"http", "https"} else ""
|
|
84
|
+
except ValueError:
|
|
85
|
+
return ""
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Bounded retention and explicit operator maintenance."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime, timedelta
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import delete, select
|
|
6
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
7
|
+
|
|
8
|
+
from sm_analytics.models import AnalyticsEvent as E
|
|
9
|
+
from sm_analytics.models import AnalyticsSession as S
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
async def cleanup(
|
|
13
|
+
db: AsyncSession,
|
|
14
|
+
tenant: str,
|
|
15
|
+
*,
|
|
16
|
+
now: datetime,
|
|
17
|
+
retention_days: int = 90,
|
|
18
|
+
batch_size: int = 5000,
|
|
19
|
+
) -> int:
|
|
20
|
+
cutoff = now - timedelta(days=retention_days)
|
|
21
|
+
ids = select(E.id).where(E.tenant_id == tenant, E.created_at < cutoff).limit(batch_size)
|
|
22
|
+
result = await db.execute(delete(E).where(E.tenant_id == tenant, E.id.in_(ids)))
|
|
23
|
+
sessions = (
|
|
24
|
+
select(S.id)
|
|
25
|
+
.where(
|
|
26
|
+
S.tenant_id == tenant,
|
|
27
|
+
S.last_seen < cutoff,
|
|
28
|
+
~select(E.id).where(E.tenant_id == tenant, E.session_id == S.id).exists(),
|
|
29
|
+
)
|
|
30
|
+
.limit(batch_size)
|
|
31
|
+
)
|
|
32
|
+
await db.execute(delete(S).where(S.tenant_id == tenant, S.id.in_(sessions)))
|
|
33
|
+
return result.rowcount
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Single scoped write path for pageviews and custom events."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime, timedelta
|
|
4
|
+
|
|
5
|
+
from simple_module_db import mark_written
|
|
6
|
+
from sqlalchemy import select, update
|
|
7
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
8
|
+
|
|
9
|
+
from sm_analytics.collection.privacy import canonical_path, referrer_host, user_agent, visitor_key
|
|
10
|
+
from sm_analytics.core.geo import GeoResolver
|
|
11
|
+
from sm_analytics.models import AnalyticsEvent, AnalyticsProperty, AnalyticsSession
|
|
12
|
+
from sm_analytics.web.schemas import CollectIn
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
async def collect(
|
|
16
|
+
db: AsyncSession,
|
|
17
|
+
data: CollectIn,
|
|
18
|
+
*,
|
|
19
|
+
tenant: str,
|
|
20
|
+
ip: str,
|
|
21
|
+
ua: str,
|
|
22
|
+
secret: str,
|
|
23
|
+
geo: GeoResolver,
|
|
24
|
+
now: datetime,
|
|
25
|
+
source_origin: str | None = None,
|
|
26
|
+
) -> bool:
|
|
27
|
+
# Serialize a property's writes, including on SQLite where FOR UPDATE is ignored.
|
|
28
|
+
result = await db.execute(
|
|
29
|
+
update(AnalyticsProperty)
|
|
30
|
+
.where(
|
|
31
|
+
AnalyticsProperty.id == data.property_id,
|
|
32
|
+
AnalyticsProperty.tenant_id == tenant,
|
|
33
|
+
AnalyticsProperty.enabled.is_(True),
|
|
34
|
+
)
|
|
35
|
+
.values(enabled=AnalyticsProperty.enabled)
|
|
36
|
+
)
|
|
37
|
+
if not result.rowcount:
|
|
38
|
+
return False
|
|
39
|
+
prop = await db.scalar(
|
|
40
|
+
select(AnalyticsProperty)
|
|
41
|
+
.where(AnalyticsProperty.id == data.property_id, AnalyticsProperty.tenant_id == tenant)
|
|
42
|
+
.execution_options(populate_existing=True)
|
|
43
|
+
)
|
|
44
|
+
if source_origin is not None and source_origin not in prop.origins:
|
|
45
|
+
return False
|
|
46
|
+
path = canonical_path(data.path, prop.route_patterns, prop.kind)
|
|
47
|
+
if path is None or (data.kind == "event" and data.name not in prop.event_allowlist):
|
|
48
|
+
return False
|
|
49
|
+
duplicate = await db.scalar(
|
|
50
|
+
select(AnalyticsEvent.id).where(
|
|
51
|
+
AnalyticsEvent.tenant_id == tenant,
|
|
52
|
+
AnalyticsEvent.property_id == prop.id,
|
|
53
|
+
AnalyticsEvent.event_id == str(data.event_id),
|
|
54
|
+
)
|
|
55
|
+
)
|
|
56
|
+
if duplicate:
|
|
57
|
+
return False
|
|
58
|
+
browser, os, device = user_agent(ua)
|
|
59
|
+
visitor = visitor_key(secret, tenant, prop.id, ip, browser, now)
|
|
60
|
+
session = await db.scalar(
|
|
61
|
+
select(AnalyticsSession)
|
|
62
|
+
.where(
|
|
63
|
+
AnalyticsSession.tenant_id == tenant,
|
|
64
|
+
AnalyticsSession.property_id == prop.id,
|
|
65
|
+
AnalyticsSession.visitor == visitor,
|
|
66
|
+
AnalyticsSession.last_seen > now - timedelta(minutes=30),
|
|
67
|
+
)
|
|
68
|
+
.order_by(AnalyticsSession.last_seen.desc())
|
|
69
|
+
.limit(1)
|
|
70
|
+
)
|
|
71
|
+
if session is None:
|
|
72
|
+
session = AnalyticsSession(
|
|
73
|
+
tenant_id=tenant, property_id=prop.id, visitor=visitor, started_at=now, last_seen=now
|
|
74
|
+
)
|
|
75
|
+
db.add(session)
|
|
76
|
+
await db.flush()
|
|
77
|
+
session.last_seen = now
|
|
78
|
+
properties = {
|
|
79
|
+
k: v for k, v in data.properties.items() if k in prop.event_allowlist.get(data.name, [])
|
|
80
|
+
}
|
|
81
|
+
utm = {k: v for k, v in data.utm.items() if k in prop.utm_parameters}
|
|
82
|
+
location = geo.lookup(ip)
|
|
83
|
+
db.add(
|
|
84
|
+
AnalyticsEvent(
|
|
85
|
+
tenant_id=tenant,
|
|
86
|
+
property_id=prop.id,
|
|
87
|
+
session_id=session.id,
|
|
88
|
+
event_id=str(data.event_id),
|
|
89
|
+
visitor=visitor,
|
|
90
|
+
created_at=now,
|
|
91
|
+
kind=data.kind,
|
|
92
|
+
path=path,
|
|
93
|
+
name=data.name,
|
|
94
|
+
properties=properties,
|
|
95
|
+
referrer=referrer_host(data.referrer),
|
|
96
|
+
browser=browser,
|
|
97
|
+
os=os,
|
|
98
|
+
device=device,
|
|
99
|
+
**utm,
|
|
100
|
+
**location.fields(),
|
|
101
|
+
)
|
|
102
|
+
)
|
|
103
|
+
await db.flush()
|
|
104
|
+
mark_written(db)
|
|
105
|
+
return True
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Analytics services."""
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Registration identifiers and ingestion limits."""
|
|
2
|
+
|
|
3
|
+
PACKAGE = "sm_analytics"
|
|
4
|
+
MODULE_NAME = "Analytics"
|
|
5
|
+
_MODULE_SETTINGS = "Settings"
|
|
6
|
+
API_PREFIX = "/api/analytics"
|
|
7
|
+
VIEW_PREFIX = "/analytics"
|
|
8
|
+
PERM_VIEW = "analytics.view"
|
|
9
|
+
PERM_MANAGE = "analytics.manage"
|
|
10
|
+
_PAGE_DASHBOARD = "Analytics/Dashboard"
|
|
11
|
+
COLLECT_PATH = f"{API_PREFIX}/collect"
|
|
12
|
+
CONFIG_PATH = f"{API_PREFIX}/config"
|
|
13
|
+
MAX_BODY_BYTES = 8192
|
|
14
|
+
UTM_PARAMETERS = frozenset({"utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"})
|
|
15
|
+
EXCLUDED_SEGMENTS = frozenset({"auth", "login", "logout", "register", "settings", "analytics"})
|
sm_analytics/core/geo.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Local GeoIP resolution; raw addresses never leave this call."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ipaddress
|
|
6
|
+
import logging
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
from dataclasses import asdict, dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Location:
|
|
18
|
+
country: str = ""
|
|
19
|
+
country_name: str = ""
|
|
20
|
+
region: str = ""
|
|
21
|
+
region_name: str = ""
|
|
22
|
+
city: str = ""
|
|
23
|
+
city_name: str = ""
|
|
24
|
+
|
|
25
|
+
def fields(self) -> dict[str, str]:
|
|
26
|
+
return asdict(self)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _reader(path: str) -> Any:
|
|
30
|
+
from geoip2.database import Reader
|
|
31
|
+
|
|
32
|
+
return Reader(path)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class GeoResolver:
|
|
36
|
+
def __init__(self, path: str = "", enabled: bool = False, reader_factory: Any = _reader):
|
|
37
|
+
self.path = path
|
|
38
|
+
self.enabled = enabled
|
|
39
|
+
self._factory = reader_factory
|
|
40
|
+
self._reader: Any = None
|
|
41
|
+
self._signature: tuple | None = None
|
|
42
|
+
self._failed: tuple | None = None
|
|
43
|
+
self._status = "disabled"
|
|
44
|
+
self._age: int | None = None
|
|
45
|
+
self._lock = threading.Lock()
|
|
46
|
+
|
|
47
|
+
def _refresh(self) -> None:
|
|
48
|
+
if not self.enabled:
|
|
49
|
+
self._close()
|
|
50
|
+
self._status = "disabled"
|
|
51
|
+
return
|
|
52
|
+
signature = None
|
|
53
|
+
try:
|
|
54
|
+
stat = Path(self.path).stat() if self.path else None
|
|
55
|
+
if stat is None:
|
|
56
|
+
raise FileNotFoundError
|
|
57
|
+
signature = (self.path, stat.st_ino, stat.st_mtime_ns, stat.st_size)
|
|
58
|
+
if signature == self._failed:
|
|
59
|
+
self._status = "unavailable"
|
|
60
|
+
return
|
|
61
|
+
if self._reader is not None and signature == self._signature:
|
|
62
|
+
return
|
|
63
|
+
self._close()
|
|
64
|
+
self._reader = self._factory(self.path)
|
|
65
|
+
self._signature = signature
|
|
66
|
+
self._failed = None
|
|
67
|
+
self._age = max(0, int((time.time() - self._reader.metadata().build_epoch) / 86400))
|
|
68
|
+
self._status = "stale" if self._age > 30 else "ready"
|
|
69
|
+
except Exception:
|
|
70
|
+
# No addresses or filenames in logs: the status screen explains provisioning.
|
|
71
|
+
if self._status != "unavailable":
|
|
72
|
+
logger.warning("Analytics geolocation unavailable; collecting unknown locations")
|
|
73
|
+
self._close()
|
|
74
|
+
self._failed = signature
|
|
75
|
+
self._status = "unavailable"
|
|
76
|
+
|
|
77
|
+
def lookup(self, ip: str) -> Location:
|
|
78
|
+
try:
|
|
79
|
+
if not ipaddress.ip_address(ip).is_global:
|
|
80
|
+
return Location()
|
|
81
|
+
except ValueError:
|
|
82
|
+
return Location()
|
|
83
|
+
with self._lock:
|
|
84
|
+
self._refresh()
|
|
85
|
+
if self._reader is None:
|
|
86
|
+
return Location()
|
|
87
|
+
try:
|
|
88
|
+
result = self._reader.city(ip)
|
|
89
|
+
country = result.country.iso_code or ""
|
|
90
|
+
subdivision = result.subdivisions.most_specific
|
|
91
|
+
region = (
|
|
92
|
+
f"{country}-{subdivision.iso_code}" if country and subdivision.iso_code else ""
|
|
93
|
+
)
|
|
94
|
+
return Location(
|
|
95
|
+
country,
|
|
96
|
+
result.country.name or "",
|
|
97
|
+
region,
|
|
98
|
+
subdivision.name or "",
|
|
99
|
+
str(result.city.geoname_id or ""),
|
|
100
|
+
result.city.name or "",
|
|
101
|
+
)
|
|
102
|
+
except Exception as exc:
|
|
103
|
+
# The optional reader's normal no-match exception leaves the database healthy.
|
|
104
|
+
if type(exc).__name__ != "AddressNotFoundError":
|
|
105
|
+
signature = self._signature
|
|
106
|
+
self._close()
|
|
107
|
+
self._failed = signature
|
|
108
|
+
self._status = "unavailable"
|
|
109
|
+
logger.warning(
|
|
110
|
+
"Analytics geolocation lookup failed; collecting unknown locations"
|
|
111
|
+
)
|
|
112
|
+
return Location()
|
|
113
|
+
|
|
114
|
+
def status(self) -> dict:
|
|
115
|
+
with self._lock:
|
|
116
|
+
self._refresh()
|
|
117
|
+
return {
|
|
118
|
+
"enabled": self.enabled,
|
|
119
|
+
"available": self._reader is not None,
|
|
120
|
+
"status": self._status,
|
|
121
|
+
"age_days": self._age,
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
def _close(self) -> None:
|
|
125
|
+
if self._reader is not None:
|
|
126
|
+
self._reader.close()
|
|
127
|
+
self._reader = None
|
|
128
|
+
self._signature = None
|
|
129
|
+
self._age = None
|
|
130
|
+
|
|
131
|
+
def close(self) -> None:
|
|
132
|
+
with self._lock:
|
|
133
|
+
self._close()
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Own the GeoIP reader and bounded retention task for one app."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
from contextlib import suppress
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
|
|
9
|
+
from simple_module_db import all_tenants, finalize_session, mark_written, tenant_context
|
|
10
|
+
from sqlalchemy import select
|
|
11
|
+
|
|
12
|
+
from sm_analytics.collection.retention import cleanup
|
|
13
|
+
from sm_analytics.core.geo import GeoResolver
|
|
14
|
+
from sm_analytics.core.settings import AnalyticsSettings
|
|
15
|
+
from sm_analytics.models import AnalyticsProperty
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Runtime:
|
|
22
|
+
settings: AnalyticsSettings
|
|
23
|
+
geo: GeoResolver = field(default_factory=GeoResolver)
|
|
24
|
+
task: asyncio.Task | None = None
|
|
25
|
+
|
|
26
|
+
async def sweep(self, factory) -> int:
|
|
27
|
+
with all_tenants():
|
|
28
|
+
async with factory() as db:
|
|
29
|
+
tenants = (await db.scalars(select(AnalyticsProperty.tenant_id).distinct())).all()
|
|
30
|
+
deleted = 0
|
|
31
|
+
for tenant in tenants:
|
|
32
|
+
with tenant_context(tenant):
|
|
33
|
+
async with factory() as db:
|
|
34
|
+
deleted += await cleanup(
|
|
35
|
+
db,
|
|
36
|
+
tenant,
|
|
37
|
+
now=datetime.now(UTC),
|
|
38
|
+
retention_days=self.settings.retention_days,
|
|
39
|
+
)
|
|
40
|
+
mark_written(db)
|
|
41
|
+
await finalize_session(db)
|
|
42
|
+
return deleted
|
|
43
|
+
|
|
44
|
+
async def run(self, factory) -> None:
|
|
45
|
+
while True:
|
|
46
|
+
await asyncio.sleep(60)
|
|
47
|
+
try:
|
|
48
|
+
await self.sweep(factory)
|
|
49
|
+
except Exception:
|
|
50
|
+
logger.exception("Analytics retention sweep failed")
|
|
51
|
+
|
|
52
|
+
async def stop(self) -> None:
|
|
53
|
+
if self.task is not None:
|
|
54
|
+
self.task.cancel()
|
|
55
|
+
with suppress(asyncio.CancelledError):
|
|
56
|
+
await self.task
|
|
57
|
+
self.task = None
|
|
58
|
+
self.geo.close()
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Deployment settings hydrate from the framework database, never the environment."""
|
|
2
|
+
|
|
3
|
+
from pydantic import Field
|
|
4
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class AnalyticsSettings(BaseSettings):
|
|
8
|
+
model_config = SettingsConfigDict(extra="ignore", use_attribute_docstrings=True)
|
|
9
|
+
retention_days: int = Field(default=90, ge=1, le=3650)
|
|
10
|
+
"""Days of events retained; deletion runs in bounded batches."""
|
|
11
|
+
geo_enabled: bool = True
|
|
12
|
+
"""Resolve approximate locations with a locally provisioned GeoLite2 City database."""
|
|
13
|
+
geo_database_path: str = ""
|
|
14
|
+
"""Absolute local MMDB path. No database is included in the package."""
|
|
15
|
+
scheduler_enabled: bool = Field(default=True, json_schema_extra={"requires_restart": True})
|
|
16
|
+
"""Run periodic retention cleanup in this process."""
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def settings_customise_sources(
|
|
20
|
+
cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings
|
|
21
|
+
):
|
|
22
|
+
return (init_settings,)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Bind the framework-resolved tenant, including on single-tenant hosts."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncIterator
|
|
4
|
+
|
|
5
|
+
from fastapi import HTTPException, Request
|
|
6
|
+
from simple_module_db import current_tenant_id, is_valid_tenant_id, tenant_context
|
|
7
|
+
from simple_module_hosting.tenancy import TenancyMode, tenancy_mode
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def resolved(request: Request, missing: int) -> str:
|
|
11
|
+
tenant = getattr(request.state, "tenant_id", None) or current_tenant_id.get()
|
|
12
|
+
if tenant is None and tenancy_mode(request.app) is TenancyMode.SINGLE:
|
|
13
|
+
tenant = "default"
|
|
14
|
+
if not is_valid_tenant_id(tenant):
|
|
15
|
+
raise HTTPException(missing, detail="tenant_required" if missing == 403 else "Not found")
|
|
16
|
+
return tenant
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def bind_admin(request: Request) -> AsyncIterator[str]:
|
|
20
|
+
with tenant_context(resolved(request, 403)) as tenant:
|
|
21
|
+
yield tenant
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
async def bind_public(request: Request) -> AsyncIterator[str]:
|
|
25
|
+
with tenant_context(resolved(request, 404)) as tenant:
|
|
26
|
+
yield tenant
|
sm_analytics/index.ts
ADDED