Files

78 lines
2.7 KiB
Go

package store
import (
"context"
"encoding/json/jsontext"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// SetKeyFields replaces the paths a source's events are grouped by.
func (s *Store) SetKeyFields(ctx context.Context, orgID, name string, paths jsontext.Value) error {
res, err := s.db.ExecContext(ctx, `
UPDATE events.sources SET key_fields = $3, updated_at = now() WHERE org_id = $1 AND name = $2`,
orgID, name, paths)
if err != nil {
return fmt.Errorf("save key fields: %w", err)
}
if n, err := res.RowsAffected(); err != nil || n == 0 {
return ErrNotFound
}
return nil
}
// Group is the events no trigger matched that share a key. Its source, type
// and filter are the trigger it proposes.
type Group struct {
ID uuid.UUID `db:"id"`
Source string `db:"source"`
EventType string `db:"event_type"`
Filter jsontext.Value `db:"filter"`
Count int64 `db:"count"`
FirstSeen time.Time `db:"first_seen"`
LastSeen time.Time `db:"last_seen"`
}
// NoteUnmatched adds an event no trigger matched to the group its key names,
// starting the group if it is the first, and reports whether it did. An event
// with no key (a schedule tick, which has none to give) is left out.
func NoteUnmatched(ctx context.Context, tx *sqlx.Tx, e Event) (bool, error) {
if !e.GroupKey.Valid {
return false, nil
}
var created bool
err := tx.QueryRowxContext(ctx, `
INSERT INTO events.groups (id, org_id, key, source, event_type, filter, count, first_seen, last_seen)
VALUES ($1, $2, $3, $4, $5, $6, 1, $7, $7)
ON CONFLICT (org_id, key) DO UPDATE
SET count = events.groups.count + 1,
first_seen = LEAST(events.groups.first_seen, EXCLUDED.first_seen),
last_seen = GREATEST(events.groups.last_seen, EXCLUDED.last_seen)
RETURNING xmax = 0`,
uuid.New(), e.OrgID, e.GroupKey.String, e.Source, e.Type, e.GroupFilter, e.ReceivedAt).Scan(&created)
if err != nil {
return false, fmt.Errorf("group event: %w", err)
}
return created, nil
}
// Groups returns the groups no trigger covers, newest activity first. A group
// stops being listed once a trigger exists for its source, type and filter.
func (s *Store) Groups(ctx context.Context, orgID string, limit int) ([]Group, error) {
var out []Group
if err := s.db.SelectContext(ctx, &out, `
SELECT g.id, g.source, g.event_type, g.filter, g.count, g.first_seen, g.last_seen
FROM events.groups g
WHERE g.org_id = $1 AND NOT EXISTS (
SELECT 1 FROM events.triggers t
WHERE t.org_id = g.org_id AND t.source = g.source AND t.event_type = g.event_type
AND t.filter = g.filter)
ORDER BY g.last_seen DESC LIMIT $2`, orgID, limit); err != nil {
return nil, fmt.Errorf("list groups: %w", err)
}
return out, nil
}