simple-module-analytics 0.0.15__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.
- simple_module_analytics-0.0.15/.gitignore +57 -0
- simple_module_analytics-0.0.15/PKG-INFO +57 -0
- simple_module_analytics-0.0.15/README.md +35 -0
- simple_module_analytics-0.0.15/docs/index.md +192 -0
- simple_module_analytics-0.0.15/package.json +21 -0
- simple_module_analytics-0.0.15/pyproject.toml +41 -0
- simple_module_analytics-0.0.15/sm_analytics/__init__.py +1 -0
- simple_module_analytics-0.0.15/sm_analytics/collection/__init__.py +1 -0
- simple_module_analytics-0.0.15/sm_analytics/collection/privacy.py +85 -0
- simple_module_analytics-0.0.15/sm_analytics/collection/retention.py +33 -0
- simple_module_analytics-0.0.15/sm_analytics/collection/service.py +105 -0
- simple_module_analytics-0.0.15/sm_analytics/core/__init__.py +1 -0
- simple_module_analytics-0.0.15/sm_analytics/core/constants.py +15 -0
- simple_module_analytics-0.0.15/sm_analytics/core/geo.py +133 -0
- simple_module_analytics-0.0.15/sm_analytics/core/runtime.py +58 -0
- simple_module_analytics-0.0.15/sm_analytics/core/settings.py +22 -0
- simple_module_analytics-0.0.15/sm_analytics/core/tenancy.py +26 -0
- simple_module_analytics-0.0.15/sm_analytics/index.ts +3 -0
- simple_module_analytics-0.0.15/sm_analytics/locales/de.json +118 -0
- simple_module_analytics-0.0.15/sm_analytics/locales/en.json +118 -0
- simple_module_analytics-0.0.15/sm_analytics/models/__init__.py +87 -0
- simple_module_analytics-0.0.15/sm_analytics/module.py +103 -0
- simple_module_analytics-0.0.15/sm_analytics/pages/Dashboard.tsx +164 -0
- simple_module_analytics-0.0.15/sm_analytics/reporting/__init__.py +1 -0
- simple_module_analytics-0.0.15/sm_analytics/reporting/reports.py +145 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/DateRangeControl.test.tsx +115 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/DateRangeControl.tsx +126 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/DeleteProperty.tsx +68 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/FilterChips.test.tsx +73 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/FilterChips.tsx +74 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/PropertyEditor.tsx +189 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/PropertySettings.test.tsx +96 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/PropertySettings.tsx +120 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/RankingPanel.tsx +119 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/RecentActivity.tsx +63 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/ReportExport.test.tsx +123 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/ReportExport.tsx +63 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/ReportFilters.test.tsx +85 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/ReportFilters.tsx +119 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/ReportView.test.tsx +216 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/ReportView.tsx +86 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/components/TrafficChart.tsx +123 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/utils/api.ts +52 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/utils/csrf.ts +46 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/utils/hostAdapter.test.ts +55 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/utils/hostTracker.test.ts +65 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/utils/hostTracker.ts +52 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/utils/i18n.ts +89 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/utils/reportExport.test.ts +112 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/utils/reportExport.ts +48 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/utils/tracker.test.ts +91 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/utils/tracker.ts +102 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/utils/trackingPaths.ts +36 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/utils/types.ts +55 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/utils/useAnalytics.test.tsx +224 -0
- simple_module_analytics-0.0.15/sm_analytics/ui/utils/useAnalytics.ts +111 -0
- simple_module_analytics-0.0.15/sm_analytics/web/__init__.py +1 -0
- simple_module_analytics-0.0.15/sm_analytics/web/deps.py +30 -0
- simple_module_analytics-0.0.15/sm_analytics/web/endpoints/__init__.py +1 -0
- simple_module_analytics-0.0.15/sm_analytics/web/endpoints/admin.py +115 -0
- simple_module_analytics-0.0.15/sm_analytics/web/endpoints/public.py +76 -0
- simple_module_analytics-0.0.15/sm_analytics/web/schemas.py +132 -0
- simple_module_analytics-0.0.15/tests/__init__.py +0 -0
- simple_module_analytics-0.0.15/tests/collection/__init__.py +0 -0
- simple_module_analytics-0.0.15/tests/collection/test_concurrency.py +90 -0
- simple_module_analytics-0.0.15/tests/collection/test_privacy.py +65 -0
- simple_module_analytics-0.0.15/tests/collection/test_service.py +89 -0
- simple_module_analytics-0.0.15/tests/conftest.py +33 -0
- simple_module_analytics-0.0.15/tests/core/__init__.py +0 -0
- simple_module_analytics-0.0.15/tests/core/test_geo.py +113 -0
- simple_module_analytics-0.0.15/tests/core/test_indexes.py +84 -0
- simple_module_analytics-0.0.15/tests/core/test_migration.py +45 -0
- simple_module_analytics-0.0.15/tests/core/test_operator.py +73 -0
- simple_module_analytics-0.0.15/tests/core/test_registration.py +21 -0
- simple_module_analytics-0.0.15/tests/core/test_settings.py +32 -0
- simple_module_analytics-0.0.15/tests/perf/benchmark.py +142 -0
- simple_module_analytics-0.0.15/tests/pg_support.py +16 -0
- simple_module_analytics-0.0.15/tests/reporting/__init__.py +0 -0
- simple_module_analytics-0.0.15/tests/reporting/test_postgres.py +52 -0
- simple_module_analytics-0.0.15/tests/reporting/test_reports.py +124 -0
- simple_module_analytics-0.0.15/tests/web/__init__.py +0 -0
- simple_module_analytics-0.0.15/tests/web/test_api.py +174 -0
- simple_module_analytics-0.0.15/tsconfig.json +5 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
.claude/settings.local.json
|
|
2
|
+
|
|
3
|
+
# Python
|
|
4
|
+
.venv/
|
|
5
|
+
__pycache__/
|
|
6
|
+
*.pyc
|
|
7
|
+
*.egg-info/
|
|
8
|
+
|
|
9
|
+
# Node
|
|
10
|
+
node_modules/
|
|
11
|
+
dist/
|
|
12
|
+
|
|
13
|
+
# Built module frontend bundles (force-included into wheels at build time)
|
|
14
|
+
modules/*/*/static/dist/
|
|
15
|
+
|
|
16
|
+
# Host build output and the module-pages manifest regenerated by `make gen-pages`
|
|
17
|
+
host/static/dist/
|
|
18
|
+
host/client_app/modules.manifest.json
|
|
19
|
+
host/client_app/modules.generated.ts
|
|
20
|
+
host/client_app/modules.generated.css
|
|
21
|
+
host/client_app/modules.assets.json
|
|
22
|
+
|
|
23
|
+
# Local databases. `make migrate` resolves alembic's script_location relative
|
|
24
|
+
# to the repo root, so running it the documented way leaves ./app.db here —
|
|
25
|
+
# not under host/ — and it must never be committed.
|
|
26
|
+
host/*.db
|
|
27
|
+
app.db*
|
|
28
|
+
# SQLite runs in WAL mode since framework 0.0.35 (#339): its sidecar files.
|
|
29
|
+
host/*.db-wal
|
|
30
|
+
host/*.db-shm
|
|
31
|
+
# `make beat` keeps Celery beat's schedule state in the repo root.
|
|
32
|
+
celerybeat-schedule*
|
|
33
|
+
|
|
34
|
+
# Runtime upload storage (PagebuilderSettings.media_root)
|
|
35
|
+
var/
|
|
36
|
+
# file_storage's local backend (DEFAULT_FS_ROOT = ./uploads), which the dev
|
|
37
|
+
# host creates in the repo root
|
|
38
|
+
uploads/
|
|
39
|
+
|
|
40
|
+
# Env
|
|
41
|
+
.env
|
|
42
|
+
|
|
43
|
+
# Playwright
|
|
44
|
+
playwright-report/
|
|
45
|
+
test-results/
|
|
46
|
+
.e2e-shards/
|
|
47
|
+
blob-report/
|
|
48
|
+
.playwright-mcp/
|
|
49
|
+
|
|
50
|
+
# macOS
|
|
51
|
+
.DS_Store
|
|
52
|
+
|
|
53
|
+
# QA / verify pipeline artifacts (/qa, /vf)
|
|
54
|
+
.qa/
|
|
55
|
+
.verify/
|
|
56
|
+
# Scratch database a /qa run boots against, so it never touches host/app.db.
|
|
57
|
+
qa.db*
|
|
@@ -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,35 @@
|
|
|
1
|
+
# SimpleModule Analytics
|
|
2
|
+
|
|
3
|
+
Native, tenant-scoped traffic and anonymous application events for SimpleModule
|
|
4
|
+
hosts. Includes a dashboard, daily visitor estimates, sessions, custom events,
|
|
5
|
+
referrers, campaign and device breakdowns, and optional local country/region/city
|
|
6
|
+
geolocation. Public and application tracking are separate opt-ins.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
pip install 'simple_module_analytics[geoip]'
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Install the package in your host and generate/apply that host's Alembic migration.
|
|
15
|
+
The base package also works without the GeoIP extra. For location reporting,
|
|
16
|
+
provision a GeoLite2 City MMDB file separately and configure its absolute path in
|
|
17
|
+
the database-backed Analytics settings. No IP lookup service is called.
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
Open **Analytics**, create a property, enter the exact site origin and allowed
|
|
22
|
+
route patterns, and enable tracking. New properties start paused. Application
|
|
23
|
+
routes such as `/records/:id` store the pattern instead of the record identifier.
|
|
24
|
+
The demo host includes the Inertia adapter; other hosts can use the exported
|
|
25
|
+
`startHostAnalytics`, `initAnalytics`, and `track` frontend functions.
|
|
26
|
+
|
|
27
|
+
No cookies, persistent browser identifiers, raw IP addresses or device coordinates
|
|
28
|
+
are stored. Do Not Track and Global Privacy Control are honored. Location and
|
|
29
|
+
visitor identity are estimates. Reports are tenant-restricted and require
|
|
30
|
+
`analytics.view`; property changes require `analytics.manage`. Retention defaults
|
|
31
|
+
to 90 days. Long-range reports scan raw events, so benchmark your deployment
|
|
32
|
+
before relying on interactive performance at high traffic volumes.
|
|
33
|
+
|
|
34
|
+
See [the guide](docs/index.md) for setup, custom events, metrics, privacy,
|
|
35
|
+
geolocation provisioning, retention operations and verification.
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# Analytics
|
|
2
|
+
|
|
3
|
+
Install `simple_module_analytics[geoip]` in a consuming host. The base package
|
|
4
|
+
works without GeoIP dependencies and shows location as unknown. This demo host
|
|
5
|
+
includes the GeoIP extra. Run host migrations before starting the app; migrations
|
|
6
|
+
belong to the consuming host, never to this wheel.
|
|
7
|
+
|
|
8
|
+
## Start collecting
|
|
9
|
+
|
|
10
|
+
Open **Analytics**, create a property, add the exact origin (`https://example.org`)
|
|
11
|
+
and the routes to track, then enable it. A new property is paused and has no
|
|
12
|
+
routes. Public and application properties are separate opt-ins. Use one per
|
|
13
|
+
traffic audience; overlapping properties intentionally each count a visit.
|
|
14
|
+
|
|
15
|
+
Patterns match the entire pathname. `:name` matches one nonempty segment. For
|
|
16
|
+
example `/p/:slug`, `/de/p/:slug`, `/news/:slug` or `/records/:id`. Add each language
|
|
17
|
+
prefix explicitly. Application paths are stored as the matched pattern; public
|
|
18
|
+
paths retain their slug. All query parameters and fragments are removed. Only
|
|
19
|
+
UTM parameters individually enabled on the property are accepted. Auth, login,
|
|
20
|
+
logout, register, settings and analytics path segments are excluded even if a
|
|
21
|
+
pattern includes them. Analytics stores no titles, form contents or user IDs.
|
|
22
|
+
Choose public route slugs and allowed event values accordingly: these fields can
|
|
23
|
+
still contain personal information supplied by an application.
|
|
24
|
+
|
|
25
|
+
The demo host installs the adapter in its Inertia entry point. Other hosts import
|
|
26
|
+
`startHostAnalytics` from `@simple-module-py/analytics`, passing a subscription that
|
|
27
|
+
forwards completed Inertia navigation URLs (skip Inertia's `initial` event; the
|
|
28
|
+
initializer handles initial load). Call its returned cleanup on teardown. The
|
|
29
|
+
module also exports `initAnalytics(config, url)` and `track(name, properties)` for
|
|
30
|
+
explicit integration. Configure allowed event/property names first:
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { track } from '@simple-module-py/analytics';
|
|
34
|
+
await track('download', { format: 'pdf' });
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
An event named `download` with property `format` must be declared on the property.
|
|
38
|
+
Other properties are discarded. Event names are 1–50 characters; up to 20 scalar
|
|
39
|
+
string/number/boolean values are accepted, with strings limited to 500 characters.
|
|
40
|
+
Requests are limited to 8 KiB. Collection retries and offline replay are disabled.
|
|
41
|
+
|
|
42
|
+
## Export a report
|
|
43
|
+
|
|
44
|
+
Choose a property, UTC date range and filters, then select **Export CSV** after
|
|
45
|
+
the report finishes loading. The download contains the applied property and
|
|
46
|
+
filter scope, four totals, daily pageview/event counts and every returned
|
|
47
|
+
breakdown row (up to 50 per dimension, including approved event properties).
|
|
48
|
+
Dates are inclusive UTC. Visitors and sessions retain the estimates described
|
|
49
|
+
below. Empty filters are recorded as `All`; unknown geographic values are
|
|
50
|
+
recorded separately as `Unknown`.
|
|
51
|
+
|
|
52
|
+
The CSV uses stable English column names and includes Unicode labels. Text that
|
|
53
|
+
could be interpreted as a spreadsheet formula is prefixed with an apostrophe.
|
|
54
|
+
This exports the currently loaded authorized report locally, without another
|
|
55
|
+
server query. It excludes the separate five-minute recent-activity list and is
|
|
56
|
+
not an export of every stored event. Export is unavailable during loading or
|
|
57
|
+
after an error; refresh successfully before trying again.
|
|
58
|
+
|
|
59
|
+
## Country, region and city
|
|
60
|
+
|
|
61
|
+
Provision an official GeoLite2 City MMDB file separately from the Python package.
|
|
62
|
+
Use [MaxMind's updater](https://dev.maxmind.com/geoip/updating-databases/) with its
|
|
63
|
+
credentials stored in the deployment's secret management, outside this repository.
|
|
64
|
+
Do not upload or commit the production database or credentials. Mount the MMDB
|
|
65
|
+
read-only at an absolute path available in every web process, then configure:
|
|
66
|
+
|
|
67
|
+
```sh
|
|
68
|
+
uv run python scripts/set_setting.py sm_analytics geo_database_path /srv/geoip/GeoLite2-City.mmdb
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
The path and `geo_enabled` apply at runtime. Each process reopens an atomically
|
|
72
|
+
replaced database automatically. The status screen shows availability and age;
|
|
73
|
+
older than 30 days is marked stale. Missing, corrupt or unavailable data yields
|
|
74
|
+
unknown locations without blocking collection. No historical re-geolocation runs.
|
|
75
|
+
Country and subdivision codes and city GeoNames IDs identify filters; names are
|
|
76
|
+
labels. Geographic report values are approximate network locations, not GPS.
|
|
77
|
+
Private/reserved addresses and unmatched records produce unknown values. No IP
|
|
78
|
+
is sent to a lookup service and neither addresses nor coordinates are stored.
|
|
79
|
+
Trust client addresses only through the host's configured trusted proxies; never
|
|
80
|
+
trust an arbitrary `X-Forwarded-For` or country header. Application server logs
|
|
81
|
+
are governed separately by the host logging configuration.
|
|
82
|
+
|
|
83
|
+
## Metrics, access and retention
|
|
84
|
+
|
|
85
|
+
All times and dates are UTC. Visitors are daily estimates from a property/tenant/
|
|
86
|
+
date-scoped HMAC of the trusted client address and browser family. There are no
|
|
87
|
+
cookies, persistent browser IDs or cross-day profiles. Shared networks may merge
|
|
88
|
+
people and network/browser changes may split them. Sessions end after 30 minutes
|
|
89
|
+
of inactivity or UTC midnight. Custom events contribute to visitor/session counts;
|
|
90
|
+
pageviews and custom events are separate totals. Known bot/crawler/spider agents
|
|
91
|
+
are omitted; this is not comprehensive bot detection. DNT and GPC opt out in both
|
|
92
|
+
tracker and collector.
|
|
93
|
+
|
|
94
|
+
`analytics.view` grants tenant reports; `analytics.manage` grants property writes.
|
|
95
|
+
The built-in screen needs view permission as well. Property IDs are public routing
|
|
96
|
+
identifiers, not secrets. Origin checks and rate limits reduce unwanted writes but
|
|
97
|
+
cannot prove an event came from a real browser. There are no public report links.
|
|
98
|
+
|
|
99
|
+
Reports support inclusive start/end dates (default last seven days, maximum 366),
|
|
100
|
+
path/event/geographic filters, top-50 breakdowns and the last five minutes of
|
|
101
|
+
activity. Select an event to see its allowed property breakdowns. Selecting an
|
|
102
|
+
unknown location filters empty values; leaving a selector at All does not filter.
|
|
103
|
+
Recent activity refreshes every 30 seconds while visible. No map or GPS is used.
|
|
104
|
+
|
|
105
|
+
Retention defaults to 90 days. Every minute each web process deletes at most 5000
|
|
106
|
+
expired events per tenant, then removes expired sessions with no remaining events.
|
|
107
|
+
Multiple replicas may safely run idempotent sweeps. Disable the restart-only
|
|
108
|
+
`scheduler_enabled` deployment setting when driving cleanup externally. A bounded
|
|
109
|
+
manual run uses the same stored retention value and existing host secret policy:
|
|
110
|
+
|
|
111
|
+
```sh
|
|
112
|
+
uv run python scripts/cleanup_analytics.py
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
A backlog may need repeated sweeps. Property deletion permanently removes its
|
|
116
|
+
events and sessions after confirmation in the screen; pausing keeps existing data.
|
|
117
|
+
Analytics settings are database-backed; `SM_ANALYTICS_*` variables have no effect.
|
|
118
|
+
|
|
119
|
+
## Query indexes
|
|
120
|
+
|
|
121
|
+
All report and collection predicates include a tenant. The host migration
|
|
122
|
+
`b6d4e2a0c913` adds indexes to match independently optional filters and the
|
|
123
|
+
property-independent retention sweep; consuming hosts must migrate their own
|
|
124
|
+
schema to match the module metadata.
|
|
125
|
+
|
|
126
|
+
| Statements | Index access |
|
|
127
|
+
| --- | --- |
|
|
128
|
+
| Property lookup, collection lock/update, property deletion | Property primary key; tenant is checked on the selected row |
|
|
129
|
+
| Property listing, enabled public configuration, scheduler tenant enumeration | Property `tenant_id` index; the small property list is sorted by name after filtering |
|
|
130
|
+
| Duplicate event lookup | Unique `(tenant_id, property_id, event_id)` constraint |
|
|
131
|
+
| Visitor's latest session and session deletion by property | `(property_id, tenant_id, visitor, last_seen)`; latest lookup scans backwards |
|
|
132
|
+
| Unfiltered totals, daily and ranked breakdowns, active visitors, recent events | Event `(property_id, tenant_id, created_at)`; recent events scan backwards |
|
|
133
|
+
| Standalone country, region, city, path or event-name filters | One event `(tenant_id, property_id, <filter>, created_at)` index per supported equality filter |
|
|
134
|
+
| Allowed JSON event-property breakdowns | Event-name/time index narrows the selected event; JSON extraction/grouping happens on those rows |
|
|
135
|
+
| Expired event/session candidate IDs, across every property in a tenant | Covering `(tenant_id, created_at, id)` / `(tenant_id, last_seen, id)` |
|
|
136
|
+
| Property foreign-key enforcement inside the database, without a tenant predicate | Existing event-time/session-visitor indexes now lead with `property_id`; no-match checks avoid unrelated histories |
|
|
137
|
+
| Session orphan check and session foreign-key enforcement | Event `session_id` index; the orphan query also filters tenant |
|
|
138
|
+
| Batched expiry deletion and property cascade deletion | Primary key for selected IDs; event/session property/tenant index prefixes for whole-property deletion |
|
|
139
|
+
|
|
140
|
+
Property IDs are globally unique. Leading with the property on the existing time
|
|
141
|
+
and visitor indexes supports both implicit foreign-key checks and explicit
|
|
142
|
+
queries that constrain both property and tenant; tenant-only cleanup keeps its
|
|
143
|
+
own time index.
|
|
144
|
+
|
|
145
|
+
Combined filters use a selective indexed prefix and check remaining conditions;
|
|
146
|
+
a separate index for every combination would multiply collection cost. The old
|
|
147
|
+
country/region/city hierarchy index is replaced because it cannot bound time
|
|
148
|
+
contiguously when intermediate location filters are absent. An empty Unknown
|
|
149
|
+
value uses the same equality index; All omits the predicate.
|
|
150
|
+
|
|
151
|
+
These indexes narrow matching rows; exact distinct counts, UTC date grouping,
|
|
152
|
+
JSON extraction and top-50 rankings still aggregate raw history. A wide report
|
|
153
|
+
may legitimately use a sequential scan, and ranking/date groups may need a sort.
|
|
154
|
+
No indexes are added on every displayed dimension or arbitrary JSON property.
|
|
155
|
+
Daily rollups remain the next step for consistently interactive long ranges.
|
|
156
|
+
Index creation uses normal transactional DDL and can block writes during a large
|
|
157
|
+
migration; allow maintenance time and additional disk space. Each collected event
|
|
158
|
+
also maintains the new indexes, so measure ingestion on the target deployment.
|
|
159
|
+
|
|
160
|
+
## Verification and capacity
|
|
161
|
+
|
|
162
|
+
Run `uv run pytest` from this module directory; set the repo's guarded
|
|
163
|
+
`SM_TEST_DATABASE_URL` to opt into a dedicated Postgres test database. Frontend
|
|
164
|
+
unit tests run through repository Vitest. `tests/e2e/analytics.spec.ts` is standalone.
|
|
165
|
+
A representative nine-million-event benchmark is opt-in; its results are specific
|
|
166
|
+
to the backend and hardware measured. Until measured on a deployment, 100,000
|
|
167
|
+
events/day is a design target, not a capacity guarantee.
|
|
168
|
+
|
|
169
|
+
A local 2026-11-08 benchmark reused synthetic nine-million-event histories on
|
|
170
|
+
SQLite and Postgres 16. The following compares the original index set with this
|
|
171
|
+
migration (seconds per complete service report):
|
|
172
|
+
|
|
173
|
+
| Backend | 7 days before / after | 90 days before / after | C1 committed events/s before / after |
|
|
174
|
+
| --- | --- | --- | --- |
|
|
175
|
+
| SQLite | 7.14 / 6.97 | 102.39 / 98.85 | 117.75 / 110.14 |
|
|
176
|
+
| Postgres | 3.93 / 4.33 | 55.62 / 55.94 | 120.72 / 123.02 |
|
|
177
|
+
|
|
178
|
+
After measurements use one report per range and 1000 individually committed
|
|
179
|
+
collector calls. Before report values are medians of three samples except the
|
|
180
|
+
Postgres 90-day report (one). Histories also contain 4000–5000 prior synthetic
|
|
181
|
+
collector events; these remain in after reports. Timings are cache-influenced,
|
|
182
|
+
local observations, not a statistically controlled throughput or capacity claim.
|
|
183
|
+
The SQLite write sample was about 6.5% slower; deployments must remeasure ingestion.
|
|
184
|
+
|
|
185
|
+
All analytics indexes, including primary/unique indexes, grew from 1.91 to
|
|
186
|
+
4.09 GB on SQLite and 1.42 to 2.24 GB on Postgres. Initial index additions took
|
|
187
|
+
104 / 149 seconds on SQLite / Postgres; rebuilding the two property-leading
|
|
188
|
+
indexes took another 20 / 18 seconds. Full migration time will vary. The fixture
|
|
189
|
+
uses short paths and mostly empty location codes, so other traffic can have larger indexes.
|
|
190
|
+
Selective filters and tenant-wide cleanup now have the intended range prefixes;
|
|
191
|
+
broad reports still aggregate raw history and show no material latency gain.
|
|
192
|
+
Daily rollups would be needed for consistently interactive long-range reports.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@simple-module-py/analytics",
|
|
3
|
+
"version": "0.0.15",
|
|
4
|
+
"private": true,
|
|
5
|
+
"description": "Anonymous traffic and application analytics",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./sm_analytics/index.ts"
|
|
8
|
+
},
|
|
9
|
+
"peerDependencies": {
|
|
10
|
+
"@inertiajs/react": "^3.9.1",
|
|
11
|
+
"@simple-module-py/i18n": "*",
|
|
12
|
+
"@simple-module-py/ui": "*",
|
|
13
|
+
"lucide-react": "^1.43.0",
|
|
14
|
+
"react": "^19.3.1",
|
|
15
|
+
"react-dom": "^19.3.1",
|
|
16
|
+
"recharts": "^3.10.1"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@simple-module-py/tsconfig": "*"
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "simple_module_analytics"
|
|
3
|
+
version = "0.0.15"
|
|
4
|
+
description = "Anonymous tenant-scoped web and application analytics with local GeoIP"
|
|
5
|
+
requires-python = ">=3.12"
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
keywords = ["simple-module", "analytics", "geoip", "web-analytics"]
|
|
9
|
+
dependencies = [
|
|
10
|
+
"simple_module_core>=0.0.44,<0.1",
|
|
11
|
+
"simple_module_db>=0.0.44,<0.1",
|
|
12
|
+
"simple_module_hosting>=0.0.44,<0.1",
|
|
13
|
+
"simple_module_inertia>=0.0.44,<0.1",
|
|
14
|
+
"simple_module_settings>=0.0.44,<0.1", # floor: settings module layout first shipped in 0.0.44
|
|
15
|
+
"pydantic-settings>=2.0",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.urls]
|
|
19
|
+
Repository = "https://github.com/antosubash/simple_module_python_modules"
|
|
20
|
+
|
|
21
|
+
[project.optional-dependencies]
|
|
22
|
+
geoip = ["geoip2>=5.2,<6"]
|
|
23
|
+
dev = ["pytest>=8", "pytest-asyncio>=0.24", "simple_module_test>=0.0.44,<0.1"]
|
|
24
|
+
|
|
25
|
+
[project.entry-points.simple_module]
|
|
26
|
+
analytics = "sm_analytics.module:AnalyticsModule"
|
|
27
|
+
|
|
28
|
+
[build-system]
|
|
29
|
+
requires = ["hatchling"]
|
|
30
|
+
build-backend = "hatchling.build"
|
|
31
|
+
|
|
32
|
+
[tool.hatch.build.targets.wheel]
|
|
33
|
+
packages = ["sm_analytics"]
|
|
34
|
+
exclude = ["**/*.test.ts", "**/*.test.tsx", "**/page-tests/**", "**/test-dom.tsx"]
|
|
35
|
+
|
|
36
|
+
[tool.hatch.build.targets.wheel.force-include]
|
|
37
|
+
"package.json" = "sm_analytics/package.json"
|
|
38
|
+
|
|
39
|
+
[tool.pytest.ini_options]
|
|
40
|
+
asyncio_mode = "auto"
|
|
41
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
@@ -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"})
|