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,111 @@
|
|
|
1
|
+
import { router } from '@inertiajs/react';
|
|
2
|
+
import { useEffect, useRef, useState } from 'react';
|
|
3
|
+
import { geoStatus, listProperties, loadReport } from './api';
|
|
4
|
+
import type { Filters, GeoStatus, Property, Report } from './types';
|
|
5
|
+
|
|
6
|
+
const today = () => new Date().toISOString().slice(0, 10);
|
|
7
|
+
export function useAnalytics() {
|
|
8
|
+
const [properties, setProperties] = useState<Property[]>([]);
|
|
9
|
+
const [selected, setSelected] = useState('');
|
|
10
|
+
const [filters, setFilters] = useState<Filters>(() => ({
|
|
11
|
+
start: new Date(Date.now() - 6 * 86400000).toISOString().slice(0, 10),
|
|
12
|
+
end: today(),
|
|
13
|
+
path: '',
|
|
14
|
+
event: '',
|
|
15
|
+
country: '',
|
|
16
|
+
region: '',
|
|
17
|
+
city: '',
|
|
18
|
+
}));
|
|
19
|
+
const scope = JSON.stringify([selected, filters]);
|
|
20
|
+
const [snapshot, setSnapshot] = useState<{ scope: string; data: Report } | null>(null);
|
|
21
|
+
const report = snapshot?.scope === scope ? snapshot.data : null;
|
|
22
|
+
const [geo, setGeo] = useState<GeoStatus | null>(null);
|
|
23
|
+
const [error, setError] = useState('');
|
|
24
|
+
const [loading, setLoading] = useState(true);
|
|
25
|
+
const [refresh, setRefresh] = useState(0);
|
|
26
|
+
const [listRefresh, setListRefresh] = useState(0);
|
|
27
|
+
const reportPending = useRef(false);
|
|
28
|
+
const reload = () => {
|
|
29
|
+
setListRefresh((n) => n + 1);
|
|
30
|
+
setRefresh((n) => n + 1);
|
|
31
|
+
};
|
|
32
|
+
// biome-ignore lint/correctness/useExhaustiveDependencies: listRefresh triggers a fresh property list.
|
|
33
|
+
useEffect(() => {
|
|
34
|
+
const controller = new AbortController();
|
|
35
|
+
setError('');
|
|
36
|
+
Promise.all([listProperties(controller.signal), geoStatus(controller.signal)])
|
|
37
|
+
.then(([items, status]) => {
|
|
38
|
+
if (controller.signal.aborted) return;
|
|
39
|
+
setProperties(items);
|
|
40
|
+
setGeo(status.geo);
|
|
41
|
+
setSelected((current) =>
|
|
42
|
+
items.some((item) => item.id === current) ? current : (items[0]?.id ?? ''),
|
|
43
|
+
);
|
|
44
|
+
setLoading(false);
|
|
45
|
+
})
|
|
46
|
+
.catch((reason: Error) => {
|
|
47
|
+
if (!controller.signal.aborted) {
|
|
48
|
+
setError(reason.message);
|
|
49
|
+
setLoading(false);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
return () => {
|
|
53
|
+
controller.abort();
|
|
54
|
+
};
|
|
55
|
+
}, [listRefresh]);
|
|
56
|
+
// biome-ignore lint/correctness/useExhaustiveDependencies: scope includes selected and filters; refresh triggers polling.
|
|
57
|
+
useEffect(() => {
|
|
58
|
+
if (!selected) return;
|
|
59
|
+
const controller = new AbortController();
|
|
60
|
+
setLoading(true);
|
|
61
|
+
setError('');
|
|
62
|
+
reportPending.current = true;
|
|
63
|
+
loadReport(selected, filters, controller.signal)
|
|
64
|
+
.then((next) => {
|
|
65
|
+
if (!controller.signal.aborted) setSnapshot({ scope, data: next });
|
|
66
|
+
})
|
|
67
|
+
.catch((reason: Error) => {
|
|
68
|
+
if (!controller.signal.aborted) setError(reason.message);
|
|
69
|
+
})
|
|
70
|
+
.finally(() => {
|
|
71
|
+
if (!controller.signal.aborted) {
|
|
72
|
+
reportPending.current = false;
|
|
73
|
+
setLoading(false);
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
return () => {
|
|
77
|
+
controller.abort();
|
|
78
|
+
reportPending.current = false;
|
|
79
|
+
};
|
|
80
|
+
}, [scope, refresh]);
|
|
81
|
+
useEffect(
|
|
82
|
+
() =>
|
|
83
|
+
router.on('navigate', () => {
|
|
84
|
+
setSelected('');
|
|
85
|
+
setProperties([]);
|
|
86
|
+
setSnapshot(null);
|
|
87
|
+
setLoading(true);
|
|
88
|
+
setListRefresh((n) => n + 1);
|
|
89
|
+
}),
|
|
90
|
+
[],
|
|
91
|
+
);
|
|
92
|
+
useEffect(() => {
|
|
93
|
+
const timer = setInterval(() => {
|
|
94
|
+
if (document.visibilityState === 'visible' && !reportPending.current)
|
|
95
|
+
setRefresh((n) => n + 1);
|
|
96
|
+
}, 30000);
|
|
97
|
+
return () => clearInterval(timer);
|
|
98
|
+
}, []);
|
|
99
|
+
return {
|
|
100
|
+
properties,
|
|
101
|
+
selected,
|
|
102
|
+
setSelected,
|
|
103
|
+
filters,
|
|
104
|
+
setFilters,
|
|
105
|
+
report,
|
|
106
|
+
geo,
|
|
107
|
+
error,
|
|
108
|
+
loading,
|
|
109
|
+
reload,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Analytics services."""
|
sm_analytics/web/deps.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Request-scoped settings and property access."""
|
|
2
|
+
|
|
3
|
+
from fastapi import HTTPException, Request
|
|
4
|
+
from simple_module_db import current_tenant_id
|
|
5
|
+
from sqlalchemy import select
|
|
6
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
7
|
+
|
|
8
|
+
from sm_analytics.models import AnalyticsProperty
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def tenant_id() -> str:
|
|
12
|
+
tenant = current_tenant_id.get()
|
|
13
|
+
if not tenant:
|
|
14
|
+
raise RuntimeError("Analytics entry point did not bind a tenant")
|
|
15
|
+
return tenant
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
async def property_for(db: AsyncSession, property_id: str) -> AnalyticsProperty:
|
|
19
|
+
prop = await db.scalar(
|
|
20
|
+
select(AnalyticsProperty).where(
|
|
21
|
+
AnalyticsProperty.id == property_id, AnalyticsProperty.tenant_id == tenant_id()
|
|
22
|
+
)
|
|
23
|
+
)
|
|
24
|
+
if prop is None:
|
|
25
|
+
raise HTTPException(404, "Not found")
|
|
26
|
+
return prop
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def services(request: Request):
|
|
30
|
+
return request.app.state.sm_analytics
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Analytics services."""
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Tenant-scoped property management and reporting."""
|
|
2
|
+
|
|
3
|
+
from datetime import UTC, date, datetime, timedelta
|
|
4
|
+
|
|
5
|
+
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
|
|
6
|
+
from simple_module_db import get_db, mark_written
|
|
7
|
+
from simple_module_hosting.csrf import RequiresCsrf
|
|
8
|
+
from simple_module_hosting.permissions import RequiresPermission
|
|
9
|
+
from sqlalchemy import delete, select
|
|
10
|
+
from sqlalchemy import update as sql_update
|
|
11
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
12
|
+
|
|
13
|
+
from sm_analytics.core import constants
|
|
14
|
+
from sm_analytics.core.tenancy import bind_admin
|
|
15
|
+
from sm_analytics.models import AnalyticsEvent, AnalyticsProperty, AnalyticsSession
|
|
16
|
+
from sm_analytics.reporting.reports import report
|
|
17
|
+
from sm_analytics.web.deps import property_for, services, tenant_id
|
|
18
|
+
from sm_analytics.web.schemas import PropertyIn
|
|
19
|
+
|
|
20
|
+
_VIEW = Depends(RequiresPermission(constants.PERM_VIEW))
|
|
21
|
+
_MANAGE = Depends(RequiresPermission(constants.PERM_MANAGE))
|
|
22
|
+
_CSRF = Depends(RequiresCsrf())
|
|
23
|
+
router = APIRouter(dependencies=[Depends(bind_admin)])
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@router.get("/properties", dependencies=[_VIEW])
|
|
27
|
+
async def properties(db: AsyncSession = Depends(get_db)) -> list[AnalyticsProperty]:
|
|
28
|
+
return list(
|
|
29
|
+
(
|
|
30
|
+
await db.scalars(
|
|
31
|
+
select(AnalyticsProperty)
|
|
32
|
+
.where(AnalyticsProperty.tenant_id == tenant_id())
|
|
33
|
+
.order_by(AnalyticsProperty.name)
|
|
34
|
+
)
|
|
35
|
+
).all()
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@router.post("/properties", dependencies=[_MANAGE, _CSRF], status_code=201)
|
|
40
|
+
async def create(data: PropertyIn, db: AsyncSession = Depends(get_db)) -> AnalyticsProperty:
|
|
41
|
+
prop = AnalyticsProperty(tenant_id=tenant_id(), **data.model_dump())
|
|
42
|
+
db.add(prop)
|
|
43
|
+
await db.flush()
|
|
44
|
+
return prop
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@router.put("/properties/{property_id}", dependencies=[_MANAGE, _CSRF])
|
|
48
|
+
async def update(
|
|
49
|
+
property_id: str, data: PropertyIn, db: AsyncSession = Depends(get_db)
|
|
50
|
+
) -> AnalyticsProperty:
|
|
51
|
+
prop = await property_for(db, property_id)
|
|
52
|
+
for key, value in data.model_dump().items():
|
|
53
|
+
setattr(prop, key, value)
|
|
54
|
+
await db.flush()
|
|
55
|
+
return prop
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@router.delete("/properties/{property_id}", dependencies=[_MANAGE, _CSRF], status_code=204)
|
|
59
|
+
async def remove(property_id: str, db: AsyncSession = Depends(get_db)) -> Response:
|
|
60
|
+
# Take the same parent lock as collection before taking child deletion snapshots.
|
|
61
|
+
locked = await db.execute(
|
|
62
|
+
sql_update(AnalyticsProperty)
|
|
63
|
+
.where(AnalyticsProperty.id == property_id, AnalyticsProperty.tenant_id == tenant_id())
|
|
64
|
+
.values(enabled=False)
|
|
65
|
+
)
|
|
66
|
+
if not locked.rowcount:
|
|
67
|
+
raise HTTPException(404, "Not found")
|
|
68
|
+
prop = await property_for(db, property_id)
|
|
69
|
+
for model in (AnalyticsEvent, AnalyticsSession):
|
|
70
|
+
await db.execute(
|
|
71
|
+
delete(model).where(model.tenant_id == tenant_id(), model.property_id == prop.id)
|
|
72
|
+
)
|
|
73
|
+
await db.delete(prop)
|
|
74
|
+
await db.flush()
|
|
75
|
+
mark_written(db)
|
|
76
|
+
return Response(status_code=204)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@router.get("/status", dependencies=[_VIEW])
|
|
80
|
+
async def status(request: Request) -> dict:
|
|
81
|
+
state = services(request)
|
|
82
|
+
state.geo.path = state.settings.geo_database_path
|
|
83
|
+
state.geo.enabled = state.settings.geo_enabled
|
|
84
|
+
return {"geo": state.geo.status()}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@router.get("/properties/{property_id}/report", dependencies=[_VIEW])
|
|
88
|
+
async def read_report(
|
|
89
|
+
property_id: str,
|
|
90
|
+
response: Response,
|
|
91
|
+
start: date | None = None,
|
|
92
|
+
end: date | None = None,
|
|
93
|
+
path: str | None = Query(None, max_length=500),
|
|
94
|
+
event: str | None = Query(None, max_length=50),
|
|
95
|
+
country: str | None = Query(None, max_length=2),
|
|
96
|
+
region: str | None = Query(None, max_length=20),
|
|
97
|
+
city: str | None = Query(None, max_length=20),
|
|
98
|
+
db: AsyncSession = Depends(get_db),
|
|
99
|
+
) -> dict:
|
|
100
|
+
prop = await property_for(db, property_id)
|
|
101
|
+
end = end or datetime.now(UTC).date()
|
|
102
|
+
start = start or end - timedelta(days=min(6, (end - date.min).days))
|
|
103
|
+
if end < start:
|
|
104
|
+
raise HTTPException(422, "Report end date must be on or after start date")
|
|
105
|
+
if (end - start).days > 365 or end >= date.max:
|
|
106
|
+
raise HTTPException(422, "Report dates must span at most 366 days")
|
|
107
|
+
response.headers["Cache-Control"] = "private, no-store"
|
|
108
|
+
return await report(
|
|
109
|
+
db,
|
|
110
|
+
tenant_id(),
|
|
111
|
+
prop,
|
|
112
|
+
start=start,
|
|
113
|
+
end=end,
|
|
114
|
+
filters={"path": path, "event": event, "country": country, "region": region, "city": city},
|
|
115
|
+
)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Anonymous same-origin configuration and write-only collection."""
|
|
2
|
+
|
|
3
|
+
from datetime import UTC, datetime
|
|
4
|
+
|
|
5
|
+
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
|
6
|
+
from simple_module_db import get_db
|
|
7
|
+
from sqlalchemy import select
|
|
8
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
9
|
+
|
|
10
|
+
from sm_analytics.collection.service import collect
|
|
11
|
+
from sm_analytics.core.tenancy import bind_public
|
|
12
|
+
from sm_analytics.models import AnalyticsProperty
|
|
13
|
+
from sm_analytics.web.deps import services, tenant_id
|
|
14
|
+
from sm_analytics.web.schemas import CollectIn, origin
|
|
15
|
+
|
|
16
|
+
router = APIRouter(dependencies=[Depends(bind_public)])
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def request_origin(request: Request, *, required: bool) -> str:
|
|
20
|
+
value = request.headers.get("origin")
|
|
21
|
+
if not value and not required:
|
|
22
|
+
value = str(request.base_url)
|
|
23
|
+
try:
|
|
24
|
+
return origin(value or "")
|
|
25
|
+
except ValueError as exc:
|
|
26
|
+
raise HTTPException(403, "Invalid origin") from exc
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@router.get("/config")
|
|
30
|
+
async def config(request: Request, response: Response, db: AsyncSession = Depends(get_db)) -> dict:
|
|
31
|
+
response.headers["Cache-Control"] = "private, no-store"
|
|
32
|
+
source = request_origin(request, required=False)
|
|
33
|
+
properties = (
|
|
34
|
+
await db.scalars(
|
|
35
|
+
select(AnalyticsProperty).where(
|
|
36
|
+
AnalyticsProperty.tenant_id == tenant_id(), AnalyticsProperty.enabled.is_(True)
|
|
37
|
+
)
|
|
38
|
+
)
|
|
39
|
+
).all()
|
|
40
|
+
return {
|
|
41
|
+
"properties": [
|
|
42
|
+
{
|
|
43
|
+
key: getattr(p, key)
|
|
44
|
+
for key in ("id", "kind", "route_patterns", "utm_parameters", "event_allowlist")
|
|
45
|
+
}
|
|
46
|
+
for p in properties
|
|
47
|
+
if source in p.origins
|
|
48
|
+
]
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@router.post("/collect", status_code=204)
|
|
53
|
+
async def ingest(data: CollectIn, request: Request, db: AsyncSession = Depends(get_db)) -> Response:
|
|
54
|
+
source = request_origin(request, required=True)
|
|
55
|
+
if request.headers.get("dnt") == "1" or request.headers.get("sec-gpc") == "1":
|
|
56
|
+
return Response(status_code=204)
|
|
57
|
+
ua = request.headers.get("user-agent", "")[:1000]
|
|
58
|
+
if any(token in ua.lower() for token in ("bot", "crawler", "spider")):
|
|
59
|
+
return Response(status_code=204)
|
|
60
|
+
state = services(request)
|
|
61
|
+
state.geo.path = state.settings.geo_database_path
|
|
62
|
+
state.geo.enabled = state.settings.geo_enabled
|
|
63
|
+
client = request.client.host if request.client else ""
|
|
64
|
+
secret = request.app.state.sm.settings.secret_key
|
|
65
|
+
await collect(
|
|
66
|
+
db,
|
|
67
|
+
data,
|
|
68
|
+
tenant=tenant_id(),
|
|
69
|
+
ip=client,
|
|
70
|
+
ua=ua,
|
|
71
|
+
secret=secret,
|
|
72
|
+
geo=state.geo,
|
|
73
|
+
now=datetime.now(UTC),
|
|
74
|
+
source_origin=source,
|
|
75
|
+
)
|
|
76
|
+
return Response(status_code=204, headers={"Cache-Control": "no-store"})
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Validated ingestion and property management boundaries."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
from typing import Annotated, Literal
|
|
8
|
+
from urllib.parse import urlsplit
|
|
9
|
+
from uuid import UUID
|
|
10
|
+
|
|
11
|
+
from pydantic import (
|
|
12
|
+
BaseModel,
|
|
13
|
+
ConfigDict,
|
|
14
|
+
Field,
|
|
15
|
+
StrictBool,
|
|
16
|
+
StrictFloat,
|
|
17
|
+
StrictInt,
|
|
18
|
+
StrictStr,
|
|
19
|
+
StringConstraints,
|
|
20
|
+
field_validator,
|
|
21
|
+
model_validator,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
from sm_analytics.core.constants import UTM_PARAMETERS
|
|
25
|
+
|
|
26
|
+
_NAME = re.compile(r"^[A-Za-z][A-Za-z0-9_.-]{0,49}$")
|
|
27
|
+
_SEGMENT = re.compile(r"^(?:[A-Za-z0-9_~.-]+|:[A-Za-z][A-Za-z0-9_]*)$")
|
|
28
|
+
Scalar = StrictStr | StrictBool | StrictInt | StrictFloat
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def origin(value: str) -> str:
|
|
32
|
+
parts = urlsplit(value)
|
|
33
|
+
if (
|
|
34
|
+
parts.scheme not in {"http", "https"}
|
|
35
|
+
or not parts.hostname
|
|
36
|
+
or parts.username
|
|
37
|
+
or parts.password
|
|
38
|
+
or parts.path not in {"", "/"}
|
|
39
|
+
or parts.query
|
|
40
|
+
or parts.fragment
|
|
41
|
+
):
|
|
42
|
+
raise ValueError("Expected an exact http(s) origin without a path")
|
|
43
|
+
port = parts.port
|
|
44
|
+
host = parts.hostname.lower()
|
|
45
|
+
host = f"[{host}]" if ":" in host else host
|
|
46
|
+
suffix = (
|
|
47
|
+
f":{port}" if port and (parts.scheme, port) not in {("https", 443), ("http", 80)} else ""
|
|
48
|
+
)
|
|
49
|
+
return f"{parts.scheme}://{host}{suffix}"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class PropertyIn(BaseModel):
|
|
53
|
+
model_config = ConfigDict(extra="forbid")
|
|
54
|
+
name: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=100)]
|
|
55
|
+
kind: Literal["public", "application"] = "public"
|
|
56
|
+
origins: list[str] = Field(min_length=1, max_length=20)
|
|
57
|
+
enabled: bool = False
|
|
58
|
+
route_patterns: list[str] = Field(default_factory=list, max_length=100)
|
|
59
|
+
event_allowlist: dict[str, list[str]] = Field(default_factory=dict, max_length=50)
|
|
60
|
+
utm_parameters: list[str] = Field(default_factory=list, max_length=5)
|
|
61
|
+
|
|
62
|
+
@field_validator("origins")
|
|
63
|
+
@classmethod
|
|
64
|
+
def validate_origins(cls, values: list[str]) -> list[str]:
|
|
65
|
+
return list(dict.fromkeys(origin(v) for v in values))
|
|
66
|
+
|
|
67
|
+
@field_validator("route_patterns")
|
|
68
|
+
@classmethod
|
|
69
|
+
def validate_patterns(cls, values: list[str]) -> list[str]:
|
|
70
|
+
for value in values:
|
|
71
|
+
if (
|
|
72
|
+
len(value) > 500
|
|
73
|
+
or not value.startswith("/")
|
|
74
|
+
or value.startswith("//")
|
|
75
|
+
or any(
|
|
76
|
+
not _SEGMENT.fullmatch(s) or s in {".", ".."}
|
|
77
|
+
for s in value.strip("/").split("/")
|
|
78
|
+
if s
|
|
79
|
+
)
|
|
80
|
+
):
|
|
81
|
+
raise ValueError("Use literal path segments or :name placeholders")
|
|
82
|
+
return list(dict.fromkeys(values))
|
|
83
|
+
|
|
84
|
+
@field_validator("event_allowlist")
|
|
85
|
+
@classmethod
|
|
86
|
+
def validate_events(cls, values: dict[str, list[str]]) -> dict[str, list[str]]:
|
|
87
|
+
for key, names in values.items():
|
|
88
|
+
if (
|
|
89
|
+
not _NAME.fullmatch(key)
|
|
90
|
+
or len(names) > 20
|
|
91
|
+
or any(not _NAME.fullmatch(n) for n in names)
|
|
92
|
+
):
|
|
93
|
+
raise ValueError(
|
|
94
|
+
"Invalid event or property name (max 50 characters, 20 properties)"
|
|
95
|
+
)
|
|
96
|
+
return values
|
|
97
|
+
|
|
98
|
+
@field_validator("utm_parameters")
|
|
99
|
+
@classmethod
|
|
100
|
+
def validate_utm(cls, values: list[str]) -> list[str]:
|
|
101
|
+
if set(values) - UTM_PARAMETERS:
|
|
102
|
+
raise ValueError("Unsupported UTM parameter")
|
|
103
|
+
return list(dict.fromkeys(values))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class CollectIn(BaseModel):
|
|
107
|
+
model_config = ConfigDict(extra="forbid")
|
|
108
|
+
property_id: str = Field(min_length=1, max_length=36)
|
|
109
|
+
event_id: UUID
|
|
110
|
+
kind: Literal["pageview", "event"]
|
|
111
|
+
path: str = Field(min_length=1, max_length=2000)
|
|
112
|
+
referrer: str = Field(default="", max_length=2000)
|
|
113
|
+
name: str = Field(default="", max_length=50)
|
|
114
|
+
properties: dict[str, Scalar] = Field(default_factory=dict, max_length=20)
|
|
115
|
+
utm: dict[str, str] = Field(default_factory=dict, max_length=5)
|
|
116
|
+
|
|
117
|
+
@model_validator(mode="after")
|
|
118
|
+
def validate_event(self) -> CollectIn:
|
|
119
|
+
if self.kind == "event" and not _NAME.fullmatch(self.name):
|
|
120
|
+
raise ValueError("Custom events require a valid name")
|
|
121
|
+
if self.kind == "pageview" and (self.name or self.properties):
|
|
122
|
+
raise ValueError("Pageviews cannot include event properties")
|
|
123
|
+
if any(
|
|
124
|
+
len(k) > 50
|
|
125
|
+
or (isinstance(v, str) and len(v) > 500)
|
|
126
|
+
or (isinstance(v, float) and not math.isfinite(v))
|
|
127
|
+
for k, v in self.properties.items()
|
|
128
|
+
):
|
|
129
|
+
raise ValueError("Event property exceeds its bounds")
|
|
130
|
+
if set(self.utm) - UTM_PARAMETERS or any(len(v) > 200 for v in self.utm.values()):
|
|
131
|
+
raise ValueError("Invalid campaign parameters")
|
|
132
|
+
return self
|