-
Notifications
You must be signed in to change notification settings - Fork 0
/
intent.go
382 lines (337 loc) · 8.59 KB
/
intent.go
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package dndm
import (
"context"
"io"
"log/slog"
"reflect"
"slices"
"sync"
"github.com/itohio/dndm/errors"
"google.golang.org/protobuf/proto"
)
var (
_ Intent = (*LocalIntent)(nil)
_ IntentInternal = (*LocalIntent)(nil)
_ Intent = (*FanOutIntent)(nil)
_ Intent = (*IntentRouter)(nil)
_ Intent = (*intentWrapper)(nil)
)
// IntentCallback is a function type used for callbacks upon adding an Intent.
type IntentCallback func(intent Intent, ep Endpoint) error
// Intent is an interface that defines methods to manage data provision requests.
// It encapsulates behaviors to close the intent, listen for interest on a route,
// send messages, and execute closure callbacks.
type Intent interface {
io.Closer
OnClose(func()) Intent
Route() Route
// Interest returns a channel that contains Routes that are interested in the data indicated by the intent.
// Users should start sending the data once an event is received on this channel.
Interest() <-chan Route
// Send will send a message to any recepient that indicated an interest.
Send(context.Context, proto.Message) error
}
// RemoteIntent extends Intent with a method to retrieve associated peer information.
type RemoteIntent interface {
Intent
Peer() Peer
}
// IntentInternal extends Intent with functionalities for linking and notifications.
type IntentInternal interface {
Intent
Link(chan<- proto.Message)
Notify()
Ctx() context.Context
}
// LocalIntent represents a simple intent that is local to the process.
// LocalIntent can be linked with LocalInterest or RemoteInterest.
type LocalIntent struct {
Base
route Route
notifyC chan Route
mu sync.RWMutex
linkedC chan<- proto.Message
}
// NewIntent initializes a new LocalIntent with specified context, route, and buffer size for the notifications channel.
func NewIntent(ctx context.Context, route Route, size int) *LocalIntent {
intent := &LocalIntent{
Base: NewBaseWithCtx(ctx),
route: route,
notifyC: make(chan Route, size),
}
intent.AddOnClose(func() {
close(intent.notifyC)
intent.linkedC = nil
})
return intent
}
func (t *LocalIntent) OnClose(f func()) Intent {
t.Base.AddOnClose(f)
return t
}
func (i *LocalIntent) Route() Route {
return i.route
}
func (i *LocalIntent) Interest() <-chan Route {
return i.notifyC
}
// LinkedC is used for internal debugging and race condition hunting
func (i *LocalIntent) LinkedC() chan<- proto.Message {
i.mu.RLock()
linkedC := i.linkedC
i.mu.RUnlock()
return linkedC
}
func (i *LocalIntent) Send(ctx context.Context, msg proto.Message) error {
i.mu.RLock()
linkedC := i.linkedC
i.mu.RUnlock()
if linkedC == nil {
return errors.ErrNoInterest
}
if i.route.Type() != nil {
if reflect.TypeOf(msg) != i.route.Type() {
return errors.ErrInvalidType
}
}
select {
case <-ctx.Done():
return ctx.Err()
case <-i.Ctx().Done():
return i.Ctx().Err()
case linkedC <- msg:
}
return nil
}
func (i *LocalIntent) Link(c chan<- proto.Message) {
i.mu.Lock()
if i.linkedC != nil && c != nil && i.linkedC != c {
i.mu.Unlock()
panic("Link called multiple times illegally")
}
i.linkedC = c
i.mu.Unlock()
}
func (i *LocalIntent) Notify() {
select {
case <-i.Ctx().Done():
return
case i.notifyC <- i.route:
default:
}
}
// FanOutIntent represents an Intent that manages multiple underlying intents.
// It distributes incoming messages across all registered intents and synchronizes their lifecycle.
type FanOutIntent struct {
li *LocalIntent
mu sync.RWMutex
intents []Intent
cancels []context.CancelFunc
wg sync.WaitGroup
onNotify func()
}
// NewFanOutIntent creates a FanOutIntent with given context, route, size, and optional initial intents.
func NewFanOutIntent(ctx context.Context, route Route, size int, intents ...Intent) (*FanOutIntent, error) {
ret := &FanOutIntent{
li: NewIntent(ctx, route, size),
}
for _, i := range intents {
if err := ret.AddIntent(i); err != nil {
return nil, err
}
}
ret.li.AddOnClose(func() {
ret.wg.Wait()
})
return ret, nil
}
func (i *FanOutIntent) OnClose(f func()) Intent {
i.li.Base.AddOnClose(f)
return i
}
func (i *FanOutIntent) Route() Route {
return i.li.Route()
}
func (i *FanOutIntent) Interest() <-chan Route {
return i.li.Interest()
}
func (i *FanOutIntent) Close() error {
err := i.li.Close()
i.wg.Wait()
return err
}
func (i *FanOutIntent) Ctx() context.Context {
return i.li.ctx
}
func (i *FanOutIntent) Send(ctx context.Context, msg proto.Message) error {
if reflect.TypeOf(msg) != i.Route().Type() {
return errors.ErrInvalidType
}
select {
case <-i.li.Ctx().Done():
return errors.ErrClosed
default:
}
i.mu.RLock()
defer i.mu.RUnlock()
var wg sync.WaitGroup
errarr := make([]error, len(i.intents))
for i, intent := range i.intents {
wg.Add(1)
go func(i int, intent Intent) {
errarr[i] = intent.Send(ctx, msg)
wg.Done()
}(i, intent)
}
wg.Wait()
noInterest := 0
for i, err := range errarr {
if errors.Is(err, errors.ErrNoInterest) {
noInterest++
errarr[i] = nil
}
}
if noInterest == len(i.intents) {
return errors.ErrNoInterest
}
return errors.Join(errarr...)
}
// AddIntent adds a new intent of the same type, creates a notify runner and links wrappers to it.
func (i *FanOutIntent) AddIntent(intent Intent) error {
i.mu.Lock()
defer i.mu.Unlock()
if !i.Route().Equal(intent.Route()) {
return errors.ErrInvalidRoute
}
ctx, cancel := context.WithCancel(i.li.Ctx())
i.intents = append(i.intents, intent)
i.cancels = append(i.cancels, cancel)
i.wg.Add(1)
intent.OnClose(cancel)
go i.notifyRunner(ctx, intent)
return nil
}
func (i *FanOutIntent) RemoveIntent(intent Intent) {
i.mu.Lock()
defer i.mu.Unlock()
idx := slices.Index(i.intents, intent)
if idx < 0 {
return
}
i.cancels[idx]()
i.intents = slices.Delete(i.intents, idx, idx+1)
i.cancels = slices.Delete(i.cancels, idx, idx+1)
if len(i.intents) > 0 {
return
}
i.Close()
}
func (i *FanOutIntent) notifyRunner(ctx context.Context, intent Intent) {
defer i.wg.Done()
for {
select {
case <-i.li.Ctx().Done():
return
case <-ctx.Done():
return
case <-intent.Interest():
if i.onNotify != nil {
i.onNotify()
continue
}
i.Notify()
}
}
}
func (i *FanOutIntent) Notify() {
slog.Info("FanOutIntent", "route", i.Route())
i.li.Notify()
}
// intentWrapper is a wrapper over IntentRouter that acts as multiple-in-multiple-out between multiple user-facing intents
// and e.g. a collection of same intents that belong to different endpoints.
type intentWrapper struct {
Base
router *IntentRouter
notifyC chan Route
}
func (w *intentWrapper) Route() Route {
return w.router.Route()
}
func (w *intentWrapper) OnClose(f func()) Intent {
w.Base.AddOnClose(f)
return w
}
func (w *intentWrapper) Interest() <-chan Route {
return w.notifyC
}
func (w *intentWrapper) Send(ctx context.Context, msg proto.Message) error {
return w.router.Send(ctx, msg)
}
// IntentRouter manages a collection of intents, routing messages and notifications among them.
type IntentRouter struct {
*FanOutIntent
size int
mu sync.RWMutex
wrappers []*intentWrapper
}
// NewIntentRouter creates a new IntentRouter with a given context, route, size, and optionally pre-registered intents.
func NewIntentRouter(ctx context.Context, route Route, size int, intents ...Intent) (*IntentRouter, error) {
foi, err := NewFanOutIntent(ctx, route, size, intents...)
if err != nil {
return nil, err
}
ret := &IntentRouter{
FanOutIntent: foi,
size: size,
}
foi.onNotify = ret.Notify
return ret, nil
}
// Wrap returns a wrapped intent. Messages sent to this wrapped intent will be sent to all the registered intents.
func (i *IntentRouter) Wrap() *intentWrapper {
ret := &intentWrapper{
Base: NewBaseWithCtx(i.li.Ctx()),
router: i,
notifyC: make(chan Route, i.size),
}
i.addWrapper(ret)
return ret
}
func (i *IntentRouter) addWrapper(w *intentWrapper) {
i.mu.Lock()
defer i.mu.Unlock()
w.AddOnClose(func() {
i.removeWrapper(w)
close(w.notifyC)
})
i.wrappers = append(i.wrappers, w)
}
func (i *IntentRouter) removeWrapper(w *intentWrapper) error {
i.mu.Lock()
defer i.mu.Unlock()
idx := slices.Index(i.wrappers, w)
w.router = nil
if idx >= 0 {
i.wrappers = slices.Delete(i.wrappers, idx, idx+1)
}
if len(i.wrappers) > 0 {
return nil
}
return i.Close()
}
func (i *IntentRouter) Notify() {
i.mu.RLock()
defer i.mu.RUnlock()
route := i.Route()
slog.Info("Notify wrappers", "route", route)
for _, w := range i.wrappers {
select {
case <-i.li.Ctx().Done():
return
case w.notifyC <- route:
// slog.Info("SEND notify", "route", route)
default:
// slog.Info("SKIP notify", "route", route)
}
}
}