Files
ccp/internal/store/store.go
T
adamf 667091efb0
Test and publish / publish (push) Successful in 4m27s
Test and publish / test (push) Successful in 9m45s
Expand tracker analytics and dashboard UX
2026-10-23 20:16:50 +01:00

570 lines
18 KiB
Go

// Package store wraps all PostgreSQL access.
package store
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"strconv"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"ccp/internal/ingest"
)
var ErrNotFound = errors.New("not found")
type Store struct {
pool *pgxpool.Pool
}
func New(pool *pgxpool.Pool) *Store { return &Store{pool: pool} }
func (s *Store) Ping(ctx context.Context) error { return s.pool.Ping(ctx) }
// ---- devices / API keys ----
type Device struct {
ID int64 `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
CreatedAt time.Time `json:"created_at"`
LastSeenAt *time.Time `json:"last_seen_at"`
RevokedAt *time.Time `json:"revoked_at"`
}
// HashKey returns the stored representation of an API key.
func HashKey(key string) string {
sum := sha256.Sum256([]byte(key))
return hex.EncodeToString(sum[:])
}
// CreateDevice registers a device and returns its plaintext API key, which
// is not stored and can't be recovered later.
func (s *Store) CreateDevice(ctx context.Context, name, kind string) (Device, string, error) {
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
return Device{}, "", err
}
key := "trk_" + base64.RawURLEncoding.EncodeToString(raw)
var d Device
err := s.pool.QueryRow(ctx,
`INSERT INTO devices (name, kind, api_key_hash) VALUES ($1, $2, $3)
RETURNING id, name, kind, created_at, last_seen_at, revoked_at`,
name, kind, HashKey(key),
).Scan(&d.ID, &d.Name, &d.Kind, &d.CreatedAt, &d.LastSeenAt, &d.RevokedAt)
return d, key, err
}
func (s *Store) ListDevices(ctx context.Context) ([]Device, error) {
rows, err := s.pool.Query(ctx,
`SELECT id, name, kind, created_at, last_seen_at, revoked_at FROM devices ORDER BY id`)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, func(r pgx.CollectableRow) (Device, error) {
var d Device
err := r.Scan(&d.ID, &d.Name, &d.Kind, &d.CreatedAt, &d.LastSeenAt, &d.RevokedAt)
return d, err
})
}
func (s *Store) RevokeDevice(ctx context.Context, name string) error {
tag, err := s.pool.Exec(ctx,
`UPDATE devices SET revoked_at = now() WHERE name = $1 AND revoked_at IS NULL`, name)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
// DeviceByKey authenticates an API key and records that the device was seen.
func (s *Store) DeviceByKey(ctx context.Context, key string) (Device, error) {
var d Device
err := s.pool.QueryRow(ctx,
`UPDATE devices SET last_seen_at = now()
WHERE api_key_hash = $1 AND revoked_at IS NULL
RETURNING id, name, kind, created_at, last_seen_at, revoked_at`,
HashKey(key),
).Scan(&d.ID, &d.Name, &d.Kind, &d.CreatedAt, &d.LastSeenAt, &d.RevokedAt)
if errors.Is(err, pgx.ErrNoRows) {
return d, ErrNotFound
}
return d, err
}
// ---- ingest ----
// InsertActivities stores activities, skipping ones already stored with the
// 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 (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
// other's moves. Moving to the place the device is already in changes
// nothing, so repeated geofence triggers are harmless. It returns the place
// the device is now in and whether anything changed.
func (s *Store) MoveTo(ctx context.Context, deviceID int64, at time.Time, dest func(cur string) string) (string, bool, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
return "", false, err
}
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, deviceID); err != nil {
return "", false, err
}
cur, err := currentPlace(ctx, tx, deviceID)
if err != nil {
return "", false, err
}
label := dest(cur.Label)
if cur.ID != 0 {
if cur.Label == label {
return label, false, nil
}
// Out-of-order events would otherwise make a negative interval.
at = maxTime(at, cur.StartedAt)
if _, err := tx.Exec(ctx,
`UPDATE activities SET ended_at = $2, attrs = attrs - 'open' WHERE id = $1`,
cur.ID, at); err != nil {
return "", false, err
}
}
// Each open interval is closed exactly once, so the one this move closes
// identifies it. (A timestamp wouldn't: clamped events can share one.)
if _, err := tx.Exec(ctx, `INSERT INTO activities
(device_id, source, kind, label, started_at, ended_at, attrs, external_id)
VALUES ($1, $2, $3, $4, $5, $5, '{"open": true}', $6)`,
deviceID, ingest.LocationSource, ingest.PlaceKind, label, at,
fmt.Sprintf("move|%d|%d", deviceID, cur.ID)); err != nil {
return "", false, err
}
return label, true, tx.Commit(ctx)
}
type openPlace struct {
ID int64
Label string
StartedAt time.Time
}
func currentPlace(ctx context.Context, tx pgx.Tx, deviceID int64) (openPlace, error) {
var p openPlace
err := tx.QueryRow(ctx,
`SELECT id, label, started_at FROM activities
WHERE device_id = $1 AND source = $2 AND attrs ? 'open'`,
deviceID, ingest.LocationSource).Scan(&p.ID, &p.Label, &p.StartedAt)
if errors.Is(err, pgx.ErrNoRows) {
return p, nil
}
return p, err
}
func maxTime(a, b time.Time) time.Time {
if a.After(b) {
return a
}
return b
}
func (s *Store) sendBatch(ctx context.Context, b *pgx.Batch) (int64, error) {
if b.Len() == 0 {
return 0, nil
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return 0, err
}
defer tx.Rollback(ctx)
br := tx.SendBatch(ctx, b)
var inserted int64
for range b.Len() {
tag, err := br.Exec()
if err != nil {
br.Close()
return 0, err
}
inserted += tag.RowsAffected()
}
if err := br.Close(); err != nil {
return 0, err
}
return inserted, tx.Commit(ctx)
}
// ---- queries ----
type StoredActivity struct {
ID int64 `json:"id"`
Device string `json:"device"`
Source string `json:"source"`
Kind string `json:"kind"`
Label string `json:"label"`
StartedAt time.Time `json:"started_at"`
EndedAt time.Time `json:"ended_at"`
DurationS int `json:"duration_s"`
Attrs map[string]any `json:"attrs"`
}
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
// with ended_at = started_at) as running until now.
const effectiveEnd = `(CASE WHEN attrs ? 'open' THEN greatest(ended_at, now()) ELSE ended_at END)`
// 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, 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)
`+cursorClause+`
ORDER BY a.started_at, a.id
LIMIT $`+strconv.Itoa(limitArg), args...)
if err != nil {
return nil, nil, err
}
type activityRow struct {
activity StoredActivity
started time.Time
}
rowsOut, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (activityRow, error) {
var a StoredActivity
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 {
Source string `json:"source"`
Kind string `json:"kind"`
Label string `json:"label"`
Seconds int64 `json:"seconds"`
}
// Totals sums activity time per (source, kind, label), counting only the
// part of each interval that falls inside [from, to).
func (s *Store) Totals(ctx context.Context, from, to time.Time) ([]Total, error) {
rows, err := s.pool.Query(ctx,
`SELECT source, kind, label,
sum(extract(epoch FROM least(end_at, $2) - greatest(started_at, $1)))::bigint AS seconds
FROM (SELECT *, `+effectiveEnd+` AS end_at FROM activities) a
WHERE started_at < $2 AND end_at > $1
GROUP BY source, kind, label
ORDER BY seconds DESC`,
from, to)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, pgx.RowToStructByPos[Total])
}
// ---- goals ----
type Goal struct {
ID int64 `json:"id"`
Kind string `json:"kind"`
Label string `json:"label"`
Op string `json:"op"`
TargetS int64 `json:"target_s"`
Period string `json:"period"`
}
func (s *Store) Goals(ctx context.Context) ([]Goal, error) {
rows, err := s.pool.Query(ctx,
`SELECT id, kind, label, op, target_s, period FROM goals ORDER BY id`)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, pgx.RowToStructByPos[Goal])
}
func (s *Store) CreateGoal(ctx context.Context, g Goal) (Goal, error) {
err := s.pool.QueryRow(ctx,
`INSERT INTO goals (kind, label, op, target_s) VALUES ($1, $2, $3, $4)
RETURNING id, period`,
g.Kind, g.Label, g.Op, g.TargetS,
).Scan(&g.ID, &g.Period)
if err != nil {
return g, fmt.Errorf("create goal: %w", err)
}
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 {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
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)
}