// Package store wraps all PostgreSQL access. package store import ( "context" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "errors" "fmt" "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 (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 { 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) } return s.sendBatch(ctx, b) } // InsertSamples stores samples with the same idempotency rules as activities. func (s *Store) InsertSamples(ctx context.Context, deviceID int64, samples []ingest.Sample) (int64, error) { b := &pgx.Batch{} for _, m := 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 (source, external_id) DO NOTHING`, deviceID, m.Source, m.Metric, m.TS, m.Value, m.Unit, m.ExternalID) } return s.sendBatch(ctx, 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 } // Activities returns activities overlapping [From, To), oldest first. func (s *Store) Activities(ctx context.Context, f ActivityFilter) ([]StoredActivity, error) { rows, err := s.pool.Query(ctx, `SELECT a.id, d.name, a.source, a.kind, a.label, a.started_at, a.ended_at, a.duration_s, a.attrs FROM activities a JOIN devices d ON d.id = a.device_id WHERE a.started_at < $2 AND a.ended_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) if err != nil { return nil, err } return pgx.CollectRows(rows, func(r pgx.CollectableRow) (StoredActivity, 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 }) } 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(ended_at, $2) - greatest(started_at, $1)))::bigint AS seconds FROM activities WHERE started_at < $2 AND ended_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) 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 }