Skip to content

Commit 16690f7

Browse files
committed
feat(activity): track domain read requests
1 parent 6d2a057 commit 16690f7

14 files changed

Lines changed: 265 additions & 8 deletions

File tree

‎AGENTS.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ GET /api/v1/concepts/* — 单取
4343
GET /api/v1/links/* — 出链 + 反向引用(links 拆为独立顶层资源)
4444
PUT /api/v1/links/* — 替换概念的出链
4545
GET /api/v1/domains/{domain}/export — OKF bundle 导出(NDJSON 概念流,由客户端本地渲染文件树)
46-
GET /api/v1/domains/{domain}/activity — 日粒度 concept 创建/更新活跃度(默认 30 天,最多 365 天)
46+
GET /api/v1/domains/{domain}/activity — 日粒度创建、更新和成功知识读取请求(默认 30 天,最多 365 天)
4747
GET /api/v1/domains — 领域清单(concept 数及聚合 created_at/updated_at)
4848
PUT /api/v1/domains/{domain} — 创建/更新 README、schema、visibility
4949
DELETE /api/v1/domains/{domain} — 级联删除 domain 全部数据
@@ -58,6 +58,7 @@ GET /api/v1/health — 健康检查
5858
concepts — 主干表,每个 concept 一行(= OKF concept)
5959
links — 有向关系(from_id → to_id,容忍断链)
6060
revisions — 变更历史(替代 git)
61+
domain_read_stats — domain 每日成功知识读取请求聚合(不保存访问者身份)
6162
```
6263

6364
详见 `internal/model/` 和 `migrations/001_init.sql`。

‎frontend/src/api/client.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ export interface DomainActivityPoint {
2626
date: string;
2727
created: number;
2828
updated: number;
29+
reads: number;
2930
activity: number;
3031
}
3132

‎frontend/src/components/ActivityChart.tsx‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ const PANEL_GAP = 10;
88
const PANEL_PADDING_X = 14;
99
const PANEL_PADDING_TOP = 32;
1010
const PANEL_PADDING_BOTTOM = 12;
11-
const CHART_HEIGHT = PANEL_HEIGHT * 3 + PANEL_GAP * 2;
1211

1312
type PlotPoint = { x: number; y: number };
1413

@@ -20,11 +19,14 @@ type ActivitySeries = {
2019
};
2120

2221
const series: ActivitySeries[] = [
23-
{ id: "activity", label: "活跃", color: "#b9c9c7", value: (point) => point.activity },
24-
{ id: "created", label: "创建", color: "#9fb5b3", value: (point) => point.created },
25-
{ id: "updated", label: "更新", color: "#c8c0ad", value: (point) => point.updated },
22+
{ id: "activity", label: "变更", color: "#b9c9c7", value: (point) => point.activity },
23+
{ id: "created", label: "创建", color: "#aabdbc", value: (point) => point.created },
24+
{ id: "updated", label: "更新", color: "#91aaa7", value: (point) => point.updated },
25+
{ id: "reads", label: "读取", color: "#c8c0ad", value: (point) => point.reads },
2626
];
2727

28+
const CHART_HEIGHT = PANEL_HEIGHT * series.length + PANEL_GAP * (series.length - 1);
29+
2830
function smoothPath(points: PlotPoint[]): string {
2931
if (points.length === 0) return "";
3032
if (points.length === 1) return `M ${points[0].x.toFixed(2)} ${points[0].y.toFixed(2)}`;
@@ -92,7 +94,7 @@ export function ActivityChart({ points }: { points: DomainActivityPoint[] }) {
9294
}}
9395
>
9496
<div style={{ padding: "18px 20px 14px", display: "flex", justifyContent: "space-between", gap: 16, alignItems: "baseline", flexWrap: "wrap" }}>
95-
<Text weight="medium" style={{ color: "#e2e9e7" }}>近 30 天活跃度</Text>
97+
<Text weight="medium" style={{ color: "#e2e9e7" }}>近 30 天活动</Text>
9698
<Text size="xs" style={{ color: "rgba(216, 225, 223, 0.6)", fontVariantNumeric: "tabular-nums" }}>
9799
{formatShortDate(points[0]?.date)} — {formatShortDate(points[points.length - 1]?.date)}
98100
</Text>
@@ -102,7 +104,7 @@ export function ActivityChart({ points }: { points: DomainActivityPoint[] }) {
102104
viewBox={`0 0 ${WIDTH} ${CHART_HEIGHT}`}
103105
preserveAspectRatio="none"
104106
role="img"
105-
aria-label="Domain 近 30 天活跃度,包含活跃、创建、更新三组面积图"
107+
aria-label="Domain 近 30 天活动,包含变更、创建、更新、读取四组面积图"
106108
style={{ display: "block", width: "100%", height: `${CHART_HEIGHT}px`, padding: "0 12px", boxSizing: "border-box" }}
107109
>
108110
<defs>
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package handler
2+
3+
import (
4+
"net/http"
5+
"testing"
6+
"time"
7+
8+
"github.com/talesofai/okp/internal/config"
9+
"github.com/talesofai/okp/internal/model"
10+
"github.com/talesofai/okp/internal/testutil"
11+
)
12+
13+
func TestSuccessfulKnowledgeReadsFeedDomainActivity(t *testing.T) {
14+
db := testutil.OpenDatabase(t)
15+
previousConfig := config.C
16+
config.C = config.Config{ExecutionGrantKey: "test-key"}
17+
t.Cleanup(func() { config.C = previousConfig })
18+
19+
for _, user := range []model.User{
20+
{UUID: "reader", AuthType: "test", Role: "reader"},
21+
{UUID: "outsider", AuthType: "test", Role: "reader"},
22+
} {
23+
if err := db.Create(&user).Error; err != nil {
24+
t.Fatal(err)
25+
}
26+
}
27+
if err := db.Create(&[]model.DomainMeta{
28+
{Domain: "public", Readme: "# Public", Visibility: "public"},
29+
{Domain: "private", Readme: "# Private", Visibility: "private"},
30+
}).Error; err != nil {
31+
t.Fatal(err)
32+
}
33+
if err := db.Create(&[]model.Concept{
34+
{ID: "public/Note/one", Domain: "public", Type: "Note", Title: "One", Provenance: model.JSONMap{"source": "test", "agent": "test"}},
35+
{ID: "private/Note/hidden", Domain: "private", Type: "Note", Title: "Hidden", Provenance: model.JSONMap{"source": "test", "agent": "test"}},
36+
}).Error; err != nil {
37+
t.Fatal(err)
38+
}
39+
40+
router := NewRouter()
41+
readerToken := testExecutionToken(t, "test-key", "reader")
42+
outsiderToken := testExecutionToken(t, "test-key", "outsider")
43+
44+
assertStatus(t, testRequest(t, router, readerToken, http.MethodGet, "/api/v1/concepts?domain=public", nil), http.StatusOK)
45+
assertStatus(t, testRequest(t, router, readerToken, http.MethodGet, "/api/v1/concepts/public/Note/one", nil), http.StatusOK)
46+
assertStatus(t, testRequest(t, router, readerToken, http.MethodGet, "/api/v1/links/public/Note/one", nil), http.StatusOK)
47+
assertStatus(t, testRequest(t, router, readerToken, http.MethodGet, "/api/v1/domains/public", nil), http.StatusOK)
48+
assertStatus(t, testRequest(t, router, readerToken, http.MethodGet, "/api/v1/concepts?domain=public&q=absent", nil), http.StatusOK)
49+
50+
// Hidden/private requests and the activity endpoint itself must not inflate reads.
51+
assertStatus(t, testRequest(t, router, outsiderToken, http.MethodGet, "/api/v1/concepts/private/Note/hidden", nil), http.StatusNotFound)
52+
assertStatus(t, testRequest(t, router, outsiderToken, http.MethodGet, "/api/v1/concepts?domain=private", nil), http.StatusOK)
53+
res := testRequest(t, router, readerToken, http.MethodGet, "/api/v1/domains/public/activity?days=1", nil)
54+
assertStatus(t, res, http.StatusOK)
55+
56+
var activity struct {
57+
Points []struct {
58+
Reads int64 `json:"reads"`
59+
} `json:"points"`
60+
}
61+
decodeResponse(t, res, &activity)
62+
if len(activity.Points) != 1 || activity.Points[0].Reads != 5 {
63+
t.Fatalf("activity reads = %+v, want 5", activity.Points)
64+
}
65+
66+
var privateReads int64
67+
if err := db.Model(&model.DomainReadStat{}).Where("domain = ?", "private").Count(&privateReads).Error; err != nil {
68+
t.Fatal(err)
69+
}
70+
if privateReads != 0 {
71+
t.Fatalf("private reads should remain zero, got %d", privateReads)
72+
}
73+
74+
var publicStat model.DomainReadStat
75+
if err := db.Where("domain = ? AND date = ?", "public", time.Now().UTC().Format("2006-01-02")).First(&publicStat).Error; err != nil {
76+
t.Fatal(err)
77+
}
78+
if publicStat.Reads != 5 {
79+
t.Fatalf("stored reads = %d, want 5", publicStat.Reads)
80+
}
81+
}

‎internal/handler/router.go‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,31 @@ func writeError(w http.ResponseWriter, status int, msg string) {
9696
writeJSON(w, status, map[string]string{"error": msg})
9797
}
9898

99+
// recordDomainRead is intentionally best-effort: analytics must never turn a
100+
// successful knowledge read into an API failure.
101+
func recordDomainRead(domain string) {
102+
if err := service.RecordDomainRead(domain); err != nil {
103+
slog.Warn("record domain read failed", "domain", domain, "error", err)
104+
}
105+
}
106+
107+
// recordReadableDomainRead attributes a filtered GET only after confirming
108+
// that its domain both exists and is readable. It must not affect the caller's
109+
// response, including the existing empty-result behavior for hidden domains.
110+
func recordReadableDomainRead(r *http.Request, domain string) {
111+
if domain == "" || !auth.CanReadDomain(auth.UserIDFromContext(r), domain) {
112+
return
113+
}
114+
exists, err := service.DomainExists(domain)
115+
if err != nil {
116+
slog.Warn("domain read existence lookup failed", "domain", domain, "error", err)
117+
return
118+
}
119+
if exists {
120+
recordDomainRead(domain)
121+
}
122+
}
123+
99124
func requireReadableDomain(w http.ResponseWriter, r *http.Request, domain string) bool {
100125
exists, err := service.DomainExists(domain)
101126
if err != nil {
@@ -375,6 +400,8 @@ func listConcepts(w http.ResponseWriter, r *http.Request) {
375400
}
376401

377402
w.Header().Set("X-Total-Count", itoa(total))
403+
// A cross-domain search has no unambiguous domain to attribute, so skip it.
404+
recordReadableDomainRead(r, params.Domain)
378405
writeJSON(w, http.StatusOK, results)
379406
}
380407

@@ -390,6 +417,7 @@ func getConcept(w http.ResponseWriter, r *http.Request) {
390417
writeError(w, http.StatusNotFound, "concept 不存在: "+id)
391418
return
392419
}
420+
recordDomainRead(c.Domain)
393421
writeJSON(w, http.StatusOK, c)
394422
}
395423

@@ -437,6 +465,7 @@ func getConceptLinks(w http.ResponseWriter, r *http.Request) {
437465
}
438466
w.Header().Set("X-Total-Outgoing", itoa(totalOut))
439467
w.Header().Set("X-Total-Backlinks", itoa(totalBack))
468+
recordDomainRead(c.Domain)
440469
writeJSON(w, http.StatusOK, map[string]any{
441470
"concept_id": id,
442471
"outgoing": outgoing,
@@ -539,6 +568,7 @@ func exportDomain(w http.ResponseWriter, r *http.Request) {
539568
writeError(w, http.StatusNotFound, fmt.Sprintf("domain '%s' 下无 concept", domain))
540569
return
541570
}
571+
recordDomainRead(domain)
542572

543573
w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8")
544574
w.Header().Set("X-Total-Count", itoa(count))
@@ -647,6 +677,7 @@ func getDomainMeta(w http.ResponseWriter, r *http.Request) {
647677
writeError(w, http.StatusNotFound, "domain 没有 README: "+domain)
648678
return
649679
}
680+
recordDomainRead(domain)
650681
writeJSON(w, http.StatusOK, meta)
651682
}
652683

@@ -751,6 +782,7 @@ func sampleConcepts(w http.ResponseWriter, r *http.Request) {
751782
writeError(w, http.StatusInternalServerError, "采样失败")
752783
return
753784
}
785+
recordReadableDomainRead(r, q.Get("domain"))
754786
writeJSON(w, http.StatusOK, results)
755787
}
756788

‎internal/model/domain_read_stat.go‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package model
2+
3+
// DomainReadStat stores one UTC day's successful knowledge-read requests for a
4+
// domain. It intentionally contains no visitor or request identifiers.
5+
type DomainReadStat struct {
6+
Domain string `gorm:"primaryKey;type:text" json:"domain"`
7+
Date string `gorm:"primaryKey;type:date" json:"date"`
8+
Reads int64 `gorm:"not null;default:0" json:"reads"`
9+
}
10+
11+
func (DomainReadStat) TableName() string {
12+
return "domain_read_stats"
13+
}

‎internal/service/domain_activity.go‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ type DomainActivityPoint struct {
1515
Date string `json:"date"`
1616
Created int64 `json:"created"`
1717
Updated int64 `json:"updated"`
18+
Reads int64 `json:"reads"`
1819
Activity int64 `json:"activity"`
1920
}
2021

@@ -32,8 +33,14 @@ type conceptActivityDates struct {
3233
UpdatedAt time.Time `gorm:"column:updated_at"`
3334
}
3435

36+
type domainReadBucket struct {
37+
Date string `gorm:"column:date"`
38+
Reads int64 `gorm:"column:reads"`
39+
}
40+
3541
// GetDomainActivity groups current concepts by created_at and their latest
36-
// updated_at. The range includes today and is bounded for predictable queries.
42+
// updated_at, then joins daily successful knowledge reads. The range includes
43+
// today and is bounded for predictable queries.
3744
func GetDomainActivity(domain string, days int) (DomainActivity, error) {
3845
if domain == "" {
3946
return DomainActivity{}, fmt.Errorf("domain is required")
@@ -82,6 +89,23 @@ func getDomainActivityAt(domain string, days int, now time.Time) (DomainActivity
8289
}
8390
}
8491
}
92+
93+
var readRows []domainReadBucket
94+
if err := store.DB.Model(&model.DomainReadStat{}).
95+
Select("CAST(date AS TEXT) AS date, reads").
96+
Where("domain = ? AND date >= ? AND date < ?", domain, start.Format("2006-01-02"), end.Format("2006-01-02")).
97+
Find(&readRows).Error; err != nil {
98+
return DomainActivity{}, err
99+
}
100+
pointIndex := make(map[string]int, len(points))
101+
for i := range points {
102+
pointIndex[points[i].Date] = i
103+
}
104+
for _, row := range readRows {
105+
if i, ok := pointIndex[row.Date]; ok {
106+
points[i].Reads += row.Reads
107+
}
108+
}
85109
for i := range points {
86110
points[i].Activity = points[i].Created + points[i].Updated
87111
}

‎internal/service/domain_meta.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,9 @@ func DeleteDomain(domain string) error {
150150
if err := tx.Where("domain = ?", domain).Delete(&model.DomainMember{}).Error; err != nil {
151151
return err
152152
}
153+
if err := tx.Where("domain = ?", domain).Delete(&model.DomainReadStat{}).Error; err != nil {
154+
return err
155+
}
153156
if metaErr == nil {
154157
return tx.Delete(&meta).Error
155158
}

‎internal/service/domain_reads.go‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package service
2+
3+
import (
4+
"fmt"
5+
"time"
6+
7+
"github.com/talesofai/okp/internal/model"
8+
"github.com/talesofai/okp/internal/store"
9+
"gorm.io/gorm"
10+
"gorm.io/gorm/clause"
11+
)
12+
13+
// RecordDomainRead increments the UTC daily aggregate for a successful
14+
// domain-scoped knowledge read. It deliberately stores no visitor identity.
15+
func RecordDomainRead(domain string) error {
16+
return recordDomainReadAt(domain, time.Now().UTC())
17+
}
18+
19+
func recordDomainReadAt(domain string, at time.Time) error {
20+
if domain == "" {
21+
return fmt.Errorf("domain is required")
22+
}
23+
24+
stat := model.DomainReadStat{
25+
Domain: domain,
26+
Date: at.UTC().Format("2006-01-02"),
27+
Reads: 1,
28+
}
29+
return store.DB.Clauses(clause.OnConflict{
30+
Columns: []clause.Column{{Name: "domain"}, {Name: "date"}},
31+
DoUpdates: clause.Assignments(map[string]any{
32+
"reads": gorm.Expr("reads + ?", 1),
33+
}),
34+
}).Create(&stat).Error
35+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package service
2+
3+
import (
4+
"testing"
5+
"time"
6+
7+
"github.com/talesofai/okp/internal/testutil"
8+
)
9+
10+
func TestDomainReadsAggregateIntoDailyActivity(t *testing.T) {
11+
testutil.OpenDatabase(t)
12+
now := time.Date(2026, 8, 17, 15, 0, 0, 0, time.UTC)
13+
14+
for range 3 {
15+
if err := recordDomainReadAt("demo", now.Add(-time.Hour)); err != nil {
16+
t.Fatal(err)
17+
}
18+
}
19+
if err := recordDomainReadAt("demo", now.AddDate(0, 0, -1)); err != nil {
20+
t.Fatal(err)
21+
}
22+
if err := recordDomainReadAt("other", now); err != nil {
23+
t.Fatal(err)
24+
}
25+
26+
activity, err := getDomainActivityAt("demo", 3, now)
27+
if err != nil {
28+
t.Fatal(err)
29+
}
30+
if got := activity.Points[1].Reads; got != 1 {
31+
t.Fatalf("yesterday reads = %d, want 1", got)
32+
}
33+
if got := activity.Points[2].Reads; got != 3 {
34+
t.Fatalf("today reads = %d, want 3", got)
35+
}
36+
if got := activity.Points[2].Activity; got != 0 {
37+
t.Fatalf("content activity = %d, want 0; reads must remain separate", got)
38+
}
39+
}
40+
41+
func TestRecordDomainReadRequiresDomain(t *testing.T) {
42+
testutil.OpenDatabase(t)
43+
if err := recordDomainReadAt("", time.Now()); err == nil {
44+
t.Fatal("expected empty domain validation error")
45+
}
46+
}

0 commit comments

Comments
 (0)