Expand tracker analytics and dashboard UX
This commit is contained in:
+252
-12
@@ -9,6 +9,7 @@ import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
@@ -105,19 +106,120 @@ func (s *Store) DeviceByKey(ctx context.Context, key string) (Device, error) {
|
||||
// ---- ingest ----
|
||||
|
||||
// InsertActivities stores activities, skipping ones already stored with the
|
||||
// same (source, external_id). It returns how many rows were new.
|
||||
// same (device_id, source, external_id). It returns how many rows were new.
|
||||
func (s *Store) InsertActivities(ctx context.Context, deviceID int64, acts []ingest.Activity) (int64, error) {
|
||||
b := &pgx.Batch{}
|
||||
for _, a := range acts {
|
||||
attrs := a.Attrs
|
||||
if attrs == nil {
|
||||
attrs = map[string]any{}
|
||||
}
|
||||
b.Queue(`INSERT INTO activities
|
||||
(device_id, source, kind, label, started_at, ended_at, attrs, external_id)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
ON CONFLICT (source, external_id) DO NOTHING`,
|
||||
deviceID, a.Source, a.Kind, a.Label, a.StartedAt, a.EndedAt, a.Attrs, a.ExternalID)
|
||||
ON CONFLICT (device_id, source, external_id) DO NOTHING`,
|
||||
deviceID, a.Source, a.Kind, a.Label, a.StartedAt, a.EndedAt, attrs, a.ExternalID)
|
||||
}
|
||||
return s.sendBatch(ctx, b)
|
||||
}
|
||||
|
||||
// Sample is a point-in-time metric uploaded by a collector.
|
||||
type Sample struct {
|
||||
ID int64 `json:"id"`
|
||||
Device string `json:"device,omitempty"`
|
||||
Source string `json:"source"`
|
||||
Metric string `json:"metric"`
|
||||
TS time.Time `json:"ts"`
|
||||
Value float64 `json:"value"`
|
||||
Unit string `json:"unit"`
|
||||
ExternalID string `json:"external_id"`
|
||||
}
|
||||
|
||||
func (s *Store) InsertSamples(ctx context.Context, deviceID int64, samples []Sample) (int64, error) {
|
||||
b := &pgx.Batch{}
|
||||
for _, sample := range samples {
|
||||
b.Queue(`INSERT INTO samples (device_id, source, metric, ts, value, unit, external_id)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (device_id, source, external_id) DO NOTHING`,
|
||||
deviceID, sample.Source, sample.Metric, sample.TS, sample.Value, sample.Unit, sample.ExternalID)
|
||||
}
|
||||
return s.sendBatch(ctx, b)
|
||||
}
|
||||
|
||||
type SampleFilter struct {
|
||||
From, To time.Time
|
||||
Source, Metric string
|
||||
Limit int
|
||||
After *SampleCursor
|
||||
}
|
||||
|
||||
type SampleCursor struct {
|
||||
TS time.Time
|
||||
ID int64
|
||||
}
|
||||
|
||||
func (s *Store) SamplesPage(ctx context.Context, f SampleFilter) ([]Sample, *SampleCursor, error) {
|
||||
limit := f.Limit
|
||||
if limit < 1 {
|
||||
limit = 1000
|
||||
}
|
||||
args := []any{f.From, f.To, f.Source, f.Metric}
|
||||
clause := ""
|
||||
if f.After != nil {
|
||||
clause = " AND (s.ts, s.id) > ($5, $6)"
|
||||
args = append(args, f.After.TS, f.After.ID)
|
||||
}
|
||||
args = append(args, limit+1)
|
||||
rows, err := s.pool.Query(ctx, `SELECT s.id, d.name, s.source, s.metric, s.ts, s.value, s.unit, s.external_id
|
||||
FROM samples s JOIN devices d ON d.id = s.device_id
|
||||
WHERE s.ts >= $1 AND s.ts < $2 AND ($3 = '' OR s.source = $3) AND ($4 = '' OR s.metric = $4)`+clause+`
|
||||
ORDER BY s.ts, s.id LIMIT $`+strconv.Itoa(len(args)), args...)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
rowsOut, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (Sample, error) {
|
||||
var sample Sample
|
||||
err := r.Scan(&sample.ID, &sample.Device, &sample.Source, &sample.Metric, &sample.TS, &sample.Value, &sample.Unit, &sample.ExternalID)
|
||||
return sample, err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
more := len(rowsOut) > limit
|
||||
if more {
|
||||
rowsOut = rowsOut[:limit]
|
||||
}
|
||||
var next *SampleCursor
|
||||
if more {
|
||||
last := rowsOut[len(rowsOut)-1]
|
||||
next = &SampleCursor{TS: last.TS, ID: last.ID}
|
||||
}
|
||||
return rowsOut, next, nil
|
||||
}
|
||||
|
||||
// SampleRangeSummary returns min/max/average/count grouped by metric.
|
||||
type SampleSummary struct {
|
||||
Metric string `json:"metric"`
|
||||
Unit string `json:"unit"`
|
||||
Count int64 `json:"count"`
|
||||
Min float64 `json:"min"`
|
||||
Max float64 `json:"max"`
|
||||
Average float64 `json:"average"`
|
||||
}
|
||||
|
||||
func (s *Store) SampleSummary(ctx context.Context, from, to time.Time) ([]SampleSummary, error) {
|
||||
rows, err := s.pool.Query(ctx, `SELECT metric, min(unit), count(*), min(value), max(value), avg(value)
|
||||
FROM samples WHERE ts >= $1 AND ts < $2 GROUP BY metric ORDER BY metric`, from, to)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pgx.CollectRows(rows, func(r pgx.CollectableRow) (SampleSummary, error) {
|
||||
var out SampleSummary
|
||||
err := r.Scan(&out.Metric, &out.Unit, &out.Count, &out.Min, &out.Max, &out.Average)
|
||||
return out, err
|
||||
})
|
||||
}
|
||||
|
||||
// MoveTo records a location transition for a device: it closes the device's
|
||||
// open place interval at `at` and opens one labelled dest(current place).
|
||||
// dest is called under the device's lock, so concurrent events see each
|
||||
@@ -232,6 +334,12 @@ type ActivityFilter struct {
|
||||
From, To time.Time
|
||||
Source, Kind string // empty matches all
|
||||
Limit int
|
||||
After *ActivityCursor
|
||||
}
|
||||
|
||||
type ActivityCursor struct {
|
||||
StartedAt time.Time
|
||||
ID int64
|
||||
}
|
||||
|
||||
// effectiveEnd is an activity's end, reading open location intervals (stored
|
||||
@@ -240,25 +348,70 @@ const effectiveEnd = `(CASE WHEN attrs ? 'open' THEN greatest(ended_at, now()) E
|
||||
|
||||
// Activities returns activities overlapping [From, To), oldest first.
|
||||
func (s *Store) Activities(ctx context.Context, f ActivityFilter) ([]StoredActivity, error) {
|
||||
acts, _, err := s.activitiesPage(ctx, f)
|
||||
return acts, err
|
||||
}
|
||||
|
||||
// ActivitiesPage returns one page of activities and a cursor for the next
|
||||
// page, if one exists. Results are clipped to the requested [From, To) range.
|
||||
func (s *Store) ActivitiesPage(ctx context.Context, f ActivityFilter) ([]StoredActivity, *ActivityCursor, error) {
|
||||
return s.activitiesPage(ctx, f)
|
||||
}
|
||||
|
||||
func (s *Store) activitiesPage(ctx context.Context, f ActivityFilter) ([]StoredActivity, *ActivityCursor, error) {
|
||||
limit := f.Limit
|
||||
if limit < 1 {
|
||||
limit = 1000
|
||||
}
|
||||
args := []any{f.From, f.To, f.Source, f.Kind}
|
||||
cursorClause := ""
|
||||
if f.After != nil {
|
||||
cursorClause = " AND (a.started_at, a.id) > ($5, $6)"
|
||||
args = append(args, f.After.StartedAt, f.After.ID)
|
||||
}
|
||||
limitArg := len(args) + 1
|
||||
args = append(args, limit+1)
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT a.id, d.name, a.source, a.kind, a.label, a.started_at, a.end_at,
|
||||
extract(epoch FROM a.end_at - a.started_at)::integer, a.attrs
|
||||
`SELECT a.id, a.started_at, d.name, a.source, a.kind, a.label,
|
||||
greatest(a.started_at, $1), least(a.end_at, $2),
|
||||
extract(epoch FROM least(a.end_at, $2) - greatest(a.started_at, $1))::integer, a.attrs
|
||||
FROM (SELECT *, `+effectiveEnd+` AS end_at FROM activities) a
|
||||
JOIN devices d ON d.id = a.device_id
|
||||
WHERE a.started_at < $2 AND a.end_at > $1
|
||||
AND ($3 = '' OR a.source = $3)
|
||||
AND ($4 = '' OR a.kind = $4)
|
||||
ORDER BY a.started_at
|
||||
LIMIT $5`,
|
||||
f.From, f.To, f.Source, f.Kind, f.Limit)
|
||||
`+cursorClause+`
|
||||
ORDER BY a.started_at, a.id
|
||||
LIMIT $`+strconv.Itoa(limitArg), args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
return pgx.CollectRows(rows, func(r pgx.CollectableRow) (StoredActivity, error) {
|
||||
type activityRow struct {
|
||||
activity StoredActivity
|
||||
started time.Time
|
||||
}
|
||||
rowsOut, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (activityRow, error) {
|
||||
var a StoredActivity
|
||||
err := r.Scan(&a.ID, &a.Device, &a.Source, &a.Kind, &a.Label, &a.StartedAt, &a.EndedAt, &a.DurationS, &a.Attrs)
|
||||
return a, err
|
||||
var started time.Time
|
||||
err := r.Scan(&a.ID, &started, &a.Device, &a.Source, &a.Kind, &a.Label, &a.StartedAt, &a.EndedAt, &a.DurationS, &a.Attrs)
|
||||
return activityRow{activity: a, started: started}, err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
more := len(rowsOut) > limit
|
||||
if more {
|
||||
rowsOut = rowsOut[:limit]
|
||||
}
|
||||
acts := make([]StoredActivity, len(rowsOut))
|
||||
for i, row := range rowsOut {
|
||||
acts[i] = row.activity
|
||||
}
|
||||
var next *ActivityCursor
|
||||
if more {
|
||||
next = &ActivityCursor{StartedAt: rowsOut[len(rowsOut)-1].started, ID: rowsOut[len(rowsOut)-1].activity.ID}
|
||||
}
|
||||
return acts, next, nil
|
||||
}
|
||||
|
||||
type Total struct {
|
||||
@@ -317,6 +470,22 @@ func (s *Store) CreateGoal(ctx context.Context, g Goal) (Goal, error) {
|
||||
return g, nil
|
||||
}
|
||||
|
||||
func (s *Store) UpdateGoal(ctx context.Context, g Goal) (Goal, error) {
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`UPDATE goals SET kind = $2, label = $3, op = $4, target_s = $5
|
||||
WHERE id = $1
|
||||
RETURNING id, kind, label, op, target_s, period`,
|
||||
g.ID, g.Kind, g.Label, g.Op, g.TargetS,
|
||||
).Scan(&g.ID, &g.Kind, &g.Label, &g.Op, &g.TargetS, &g.Period)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return g, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return g, fmt.Errorf("update goal: %w", err)
|
||||
}
|
||||
return g, nil
|
||||
}
|
||||
|
||||
func (s *Store) DeleteGoal(ctx context.Context, id int64) error {
|
||||
tag, err := s.pool.Exec(ctx, `DELETE FROM goals WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
@@ -327,3 +496,74 @@ func (s *Store) DeleteGoal(ctx context.Context, id int64) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
ID int64 `json:"id"`
|
||||
PeriodStart time.Time `json:"period_start"`
|
||||
PeriodEnd time.Time `json:"period_end"`
|
||||
Model string `json:"model"`
|
||||
PromptHash string `json:"prompt_hash"`
|
||||
Body string `json:"body"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (s *Store) Reports(ctx context.Context) ([]Report, error) {
|
||||
rows, err := s.pool.Query(ctx, `SELECT id, period_start, period_end, model, prompt_hash, body, created_at
|
||||
FROM reports ORDER BY period_start DESC, id DESC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pgx.CollectRows(rows, pgx.RowToStructByPos[Report])
|
||||
}
|
||||
|
||||
func (s *Store) CreateReport(ctx context.Context, report Report) (Report, error) {
|
||||
err := s.pool.QueryRow(ctx, `INSERT INTO reports (period_start, period_end, model, prompt_hash, body)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id, created_at`, report.PeriodStart, report.PeriodEnd, report.Model, report.PromptHash, report.Body).
|
||||
Scan(&report.ID, &report.CreatedAt)
|
||||
return report, err
|
||||
}
|
||||
|
||||
type NotificationSettings struct {
|
||||
NtfyServer string `json:"ntfy_server"`
|
||||
NtfyTopic string `json:"ntfy_topic"`
|
||||
Enabled bool `json:"enabled"`
|
||||
RetentionDays int `json:"retention_days"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (s *Store) NotificationSettings(ctx context.Context) (NotificationSettings, error) {
|
||||
var settings NotificationSettings
|
||||
err := s.pool.QueryRow(ctx, `SELECT ntfy_server, ntfy_topic, enabled, retention_days, updated_at
|
||||
FROM notification_settings WHERE id`).Scan(&settings.NtfyServer, &settings.NtfyTopic, &settings.Enabled,
|
||||
&settings.RetentionDays, &settings.UpdatedAt)
|
||||
return settings, err
|
||||
}
|
||||
|
||||
func (s *Store) UpdateNotificationSettings(ctx context.Context, settings NotificationSettings) (NotificationSettings, error) {
|
||||
err := s.pool.QueryRow(ctx, `UPDATE notification_settings SET ntfy_server = $1, ntfy_topic = $2,
|
||||
enabled = $3, retention_days = $4, updated_at = now() WHERE id
|
||||
RETURNING ntfy_server, ntfy_topic, enabled, retention_days, updated_at`, settings.NtfyServer,
|
||||
settings.NtfyTopic, settings.Enabled, settings.RetentionDays).Scan(&settings.NtfyServer, &settings.NtfyTopic,
|
||||
&settings.Enabled, &settings.RetentionDays, &settings.UpdatedAt)
|
||||
return settings, err
|
||||
}
|
||||
|
||||
// PurgeBefore applies the privacy retention policy to all user data tables.
|
||||
func (s *Store) PurgeBefore(ctx context.Context, before time.Time) (int64, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var deleted int64
|
||||
for _, table := range []string{"activities", "samples", "reports"} {
|
||||
column := map[string]string{"activities": "started_at", "samples": "ts", "reports": "period_start"}[table]
|
||||
tag, err := tx.Exec(ctx, `DELETE FROM `+table+` WHERE `+column+` < $1`, before)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
deleted += tag.RowsAffected()
|
||||
}
|
||||
return deleted, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user