// 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) } // 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 } // 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) { 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 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) 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(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) 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 }