aboutsummaryrefslogtreecommitdiffstats
path: root/relay/storage/events.go
blob: cf10097070d743fff6dda8e40712120e465dcda0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package storage

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"strings"

	"axon"
)

// ErrDuplicate is returned by StoreEvent when the event ID already exists.
var ErrDuplicate = errors.New("storage: duplicate event")

// StoreEvent persists an event and its tags to the database in a single
// transaction. envelopeBytes is the verbatim msgpack representation used for
// zero-copy fanout.
func (s *Storage) StoreEvent(ctx context.Context, event *axon.Event, envelopeBytes []byte) error {
	tx, err := s.db.BeginTx(ctx, nil)
	if err != nil {
		return fmt.Errorf("storage: begin tx: %w", err)
	}
	defer tx.Rollback()

	_, err = tx.ExecContext(ctx,
		`INSERT INTO events (id, pubkey, created_at, kind, envelope_bytes) VALUES (?, ?, ?, ?, ?)`,
		event.ID, event.PubKey, event.CreatedAt, event.Kind, envelopeBytes,
	)
	if err != nil {
		if isDuplicateError(err) {
			return ErrDuplicate
		}
		return fmt.Errorf("storage: insert event: %w", err)
	}

	for _, tag := range event.Tags {
		if len(tag.Values) == 0 {
			continue
		}
		_, err = tx.ExecContext(ctx,
			`INSERT INTO tags (event_id, name, value) VALUES (?, ?, ?)`,
			event.ID, tag.Name, tag.Values[0],
		)
		if err != nil {
			return fmt.Errorf("storage: insert tag: %w", err)
		}
	}

	return tx.Commit()
}

// ExistsByID returns true if an event with the given ID is already stored.
func (s *Storage) ExistsByID(ctx context.Context, id []byte) (bool, error) {
	var n int
	err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM events WHERE id = ?`, id).Scan(&n)
	if err != nil && err != sql.ErrNoRows {
		return false, fmt.Errorf("storage: exists: %w", err)
	}
	return n > 0, nil
}

// QueryEvents executes the given filters against the database using a UNION
// query and returns matching event envelope bytes in descending created_at
// order. The effective LIMIT is the minimum non-zero Limit across all filters.
func (s *Storage) QueryEvents(ctx context.Context, filters []axon.Filter) ([][]byte, error) {
	if len(filters) == 0 {
		return nil, nil
	}

	var unions []string
	var args []interface{}
	var effectiveLimit int32

	for _, f := range filters {
		var filterArgs []interface{}
		clause := buildWhereClause(f, &filterArgs)
		sub := fmt.Sprintf(
			"SELECT e.envelope_bytes, e.created_at FROM events e WHERE %s", clause)
		unions = append(unions, sub)
		args = append(args, filterArgs...)
		if f.Limit > 0 && (effectiveLimit == 0 || f.Limit < effectiveLimit) {
			effectiveLimit = f.Limit
		}
	}

	query := strings.Join(unions, " UNION ") + " ORDER BY created_at DESC"
	if effectiveLimit > 0 {
		query += fmt.Sprintf(" LIMIT %d", effectiveLimit)
	}

	rows, err := s.db.QueryContext(ctx, query, args...)
	if err != nil {
		return nil, fmt.Errorf("storage: query: %w", err)
	}
	defer rows.Close()

	var results [][]byte
	for rows.Next() {
		var envelope []byte
		var createdAt int64
		if err := rows.Scan(&envelope, &createdAt); err != nil {
			return nil, fmt.Errorf("storage: scan: %w", err)
		}
		results = append(results, envelope)
	}
	return results, rows.Err()
}

// buildWhereClause builds the SQL WHERE clause for a single filter, appending
// bind parameters to args.
func buildWhereClause(f axon.Filter, args *[]interface{}) string {
	var conditions []string

	if len(f.IDs) > 0 {
		conditions = append(conditions, buildBlobPrefixCondition("e.id", f.IDs, args))
	}

	if len(f.Authors) > 0 {
		conditions = append(conditions, buildBlobPrefixCondition("e.pubkey", f.Authors, args))
	}

	if len(f.Kinds) > 0 {
		placeholders := make([]string, len(f.Kinds))
		for i, k := range f.Kinds {
			placeholders[i] = "?"
			*args = append(*args, k)
		}
		conditions = append(conditions, "e.kind IN ("+strings.Join(placeholders, ",")+")")
	}

	if f.Since != 0 {
		conditions = append(conditions, "e.created_at >= ?")
		*args = append(*args, f.Since)
	}

	if f.Until != 0 {
		conditions = append(conditions, "e.created_at <= ?")
		*args = append(*args, f.Until)
	}

	for _, tf := range f.Tags {
		conditions = append(conditions, buildTagJoinCondition(tf, args))
	}

	if len(conditions) == 0 {
		return "1=1"
	}
	return strings.Join(conditions, " AND ")
}

// buildBlobPrefixCondition builds an OR condition for prefix-matching a BLOB
// column. Prefix slices of exactly 32 bytes use equality; shorter slices use
// hex(column) LIKE 'HEX%'.
func buildBlobPrefixCondition(column string, prefixes [][]byte, args *[]interface{}) string {
	var orConds []string
	for _, prefix := range prefixes {
		if len(prefix) == 32 {
			orConds = append(orConds, column+" = ?")
			*args = append(*args, prefix)
		} else {
			hexPrefix := fmt.Sprintf("%X", prefix)
			orConds = append(orConds, fmt.Sprintf("hex(%s) LIKE ?", column))
			*args = append(*args, hexPrefix+"%")
		}
	}
	if len(orConds) == 1 {
		return orConds[0]
	}
	return "(" + strings.Join(orConds, " OR ") + ")"
}

// buildTagJoinCondition builds an EXISTS sub-select for a TagFilter.
func buildTagJoinCondition(tf axon.TagFilter, args *[]interface{}) string {
	if len(tf.Values) == 0 {
		*args = append(*args, tf.Name)
		return "EXISTS (SELECT 1 FROM tags t WHERE t.event_id = e.id AND t.name = ?)"
	}
	var orConds []string
	for _, v := range tf.Values {
		orConds = append(orConds, "EXISTS (SELECT 1 FROM tags t WHERE t.event_id = e.id AND t.name = ? AND t.value = ?)")
		*args = append(*args, tf.Name, v)
	}
	if len(orConds) == 1 {
		return orConds[0]
	}
	return "(" + strings.Join(orConds, " OR ") + ")"
}

func isDuplicateError(err error) bool {
	return err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed")
}