Files

79 lines
3.0 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 string, id uuid.UUID, 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 id = $2`,
orgID, id, 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,
// declared event type and filter are the trigger it proposes.
type Group struct {
ID uuid.UUID `db:"id"`
SourceID uuid.UUID `db:"source_id"`
DeclaredEventType string `db:"declared_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 || !e.SourceID.Valid {
return false, nil
}
var created bool
err := tx.QueryRowxContext(ctx, `
INSERT INTO events.groups (id, org_id, key, source_id, declared_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.SourceID.UUID, e.DeclaredEventType, 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, for the
// sources the person may see. A group stops being listed once a trigger exists
// for its source, declared event type and filter.
func (s *Store) Groups(ctx context.Context, orgID, person string, limit int) ([]Group, error) {
var out []Group
if err := s.db.SelectContext(ctx, &out, `
SELECT g.id, g.source_id, g.declared_event_type, g.filter, g.count, g.first_seen, g.last_seen
FROM events.groups g
WHERE g.org_id = $1 AND `+visibleSource+` AND NOT EXISTS (
SELECT 1 FROM events.triggers t
WHERE t.org_id = g.org_id AND t.deleted_at IS NULL AND t.source_id = g.source_id
AND t.declared_event_type = g.declared_event_type AND t.filter = g.filter)
ORDER BY g.last_seen DESC LIMIT $3`, orgID, person, limit); err != nil {
return nil, fmt.Errorf("list groups: %w", err)
}
return out, nil
}