-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtopic_runtime.go
More file actions
208 lines (194 loc) · 6.08 KB
/
Copy pathtopic_runtime.go
File metadata and controls
208 lines (194 loc) · 6.08 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package blockqueue
import (
"context"
"fmt"
"sort"
"strings"
"sync"
"sync/atomic"
"unicode"
"github.com/google/uuid"
)
// topicRuntime is an in-memory routing snapshot. Database transactions remain
// authoritative for persistence and delivery ownership.
type topicRuntime struct {
id uuid.UUID
name string
paused atomic.Bool
deleted atomic.Bool
registry atomic.Pointer[subscriberRegistry]
mu sync.Mutex
admissionMu sync.RWMutex
}
type subscriberRegistry struct {
byID map[uuid.UUID]*subscriberRuntime
byName map[string]*subscriberRuntime
}
func loadTopicRuntime(ctx context.Context, topic Topic, database *db) (*topicRuntime, error) {
subscribers, err := database.getSubscribers(ctx, subscriberFilter{TopicIDs: []uuid.UUID{topic.ID}})
if err != nil {
return nil, err
}
return buildTopicRuntime(topic, subscribers)
}
// buildTopicRuntime validates every subscriber before a control-plane
// transaction commits. Publishing the resulting registry is then infallible.
func buildTopicRuntime(topic Topic, subscribers Subscribers) (*topicRuntime, error) {
if topic.ID == uuid.Nil {
return nil, fmt.Errorf("%w: id is required", ErrInvalidTopic)
}
if !validResourceName(topic.Name) {
return nil, fmt.Errorf("%w: name must be 1-150 bytes without slashes or control characters", ErrInvalidTopic)
}
runtime := &topicRuntime{id: topic.ID, name: topic.Name}
runtime.paused.Store(topic.Paused)
registry := &subscriberRegistry{
byID: make(map[uuid.UUID]*subscriberRuntime, len(subscribers)),
byName: make(map[string]*subscriberRuntime, len(subscribers)),
}
for _, subscriber := range subscribers {
if err := validateSubscriber(subscriber, topic.ID); err != nil {
return nil, err
}
item, err := newSubscriberRuntime(subscriber)
if err != nil {
return nil, err
}
if _, exists := registry.byID[item.id]; exists {
return nil, ErrResourceConflict
}
if _, exists := registry.byName[item.name]; exists {
return nil, ErrResourceConflict
}
registry.byID[item.id] = item
registry.byName[item.name] = item
}
runtime.registry.Store(registry)
return runtime, nil
}
func (topic *topicRuntime) subscriberByName(name string) (*subscriberRuntime, bool) {
subscriber, ok := topic.registry.Load().byName[name]
return subscriber, ok
}
func (topic *topicRuntime) prepareSubscribers(subscribers Subscribers) ([]*subscriberRuntime, error) {
prepared := make([]*subscriberRuntime, 0, len(subscribers))
for _, subscriber := range subscribers {
if err := validateSubscriber(subscriber, topic.id); err != nil {
return nil, err
}
item, err := newSubscriberRuntime(subscriber)
if err != nil {
return nil, err
}
prepared = append(prepared, item)
}
current := topic.registry.Load()
for _, item := range prepared {
if _, exists := current.byID[item.id]; exists {
return nil, ErrResourceConflict
}
if _, exists := current.byName[item.name]; exists {
return nil, ErrResourceConflict
}
}
return prepared, nil
}
func validateSubscriber(subscriber Subscriber, topicID uuid.UUID) error {
if subscriber.ID == uuid.Nil {
return fmt.Errorf("%w: id is required", ErrInvalidSubscriber)
}
if subscriber.TopicID != topicID {
return fmt.Errorf("%w: topic id does not match", ErrInvalidSubscriber)
}
if !validResourceName(subscriber.Name) {
return fmt.Errorf("%w: name must be 1-150 bytes without slashes or control characters", ErrInvalidSubscriber)
}
return nil
}
func validResourceName(name string) bool {
if strings.TrimSpace(name) != name || name == "" || len([]byte(name)) > 150 || strings.ContainsRune(name, '/') {
return false
}
for _, character := range name {
if unicode.IsControl(character) {
return false
}
}
return true
}
// addPreparedSubscribers cannot fail. Callers validate the candidate snapshot
// before committing the database mutation. Callers serialize topology changes
// with topicRuntime.admissionMu and the queue registry mutex.
func (topic *topicRuntime) addPreparedSubscribers(prepared []*subscriberRuntime) {
topic.mu.Lock()
defer topic.mu.Unlock()
current := topic.registry.Load()
next := &subscriberRegistry{
byID: make(map[uuid.UUID]*subscriberRuntime, len(current.byID)+len(prepared)),
byName: make(map[string]*subscriberRuntime, len(current.byName)+len(prepared)),
}
for id, item := range current.byID {
next.byID[id] = item
}
for name, item := range current.byName {
next.byName[name] = item
}
for _, item := range prepared {
next.byID[item.id] = item
next.byName[item.name] = item
}
topic.registry.Store(next)
}
func (topic *topicRuntime) removeSubscriber(subscriber *subscriberRuntime) {
topic.mu.Lock()
defer topic.mu.Unlock()
current := topic.registry.Load()
next := &subscriberRegistry{
byID: make(map[uuid.UUID]*subscriberRuntime, len(current.byID)-1),
byName: make(map[string]*subscriberRuntime, len(current.byName)-1),
}
for id, item := range current.byID {
if id != subscriber.id {
next.byID[id] = item
}
}
for name, item := range current.byName {
if name != subscriber.name {
next.byName[name] = item
}
}
select {
case subscriber.deliveryWake <- struct{}{}:
default:
}
subscriber.deleted.Store(true)
topic.registry.Store(next)
}
func (topic *topicRuntime) subscriberStatus(ctx context.Context, database *db) (SubscriberStatuses, error) {
stats, err := database.getTopicSubscriberQueueStats(ctx, topic.id)
if err != nil {
return nil, err
}
registry := topic.registry.Load()
items := make([]*subscriberRuntime, 0, len(registry.byID))
for _, subscriber := range registry.byID {
items = append(items, subscriber)
}
sort.Slice(items, func(i, j int) bool { return items[i].name < items[j].name })
result := make(SubscriberStatuses, 0, len(items))
for _, subscriber := range items {
queueStats := stats[subscriber.id]
result = append(result, SubscriberStatus{
TopicID: topic.id,
Name: subscriber.name,
UnpublishedMessage: queueStats.Pending,
UnackedMessage: queueStats.Delivered,
})
}
return result, nil
}
func (topic *topicRuntime) notify() {
for _, subscriber := range topic.registry.Load().byID {
subscriber.notify()
}
}