/
relay.go
369 lines (309 loc) · 7.02 KB
/
relay.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
package repository
import (
"context"
"fmt"
"golang.org/x/sync/semaphore"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/nbd-wtf/go-nostr"
"github.com/samber/lo"
)
type RelayConnection struct {
URL string
Relay *nostr.Relay
Context *context.Context
Cancel *context.CancelFunc
WaitSpan time.Duration
Error chan error
}
type QueryOptions struct {
RequiredOneEvent bool
ExpectedEventCount int
ExpectedEOSECount int
TimeoutSeconds time.Duration
}
func DefaultQueryOptions() QueryOptions {
return QueryOptions{
RequiredOneEvent: true,
ExpectedEventCount: -1,
ExpectedEOSECount: 1,
TimeoutSeconds: 5,
}
}
var connections = map[string]*RelayConnection{}
// GetConnections
// Obtain relay server connection information
func GetConnections() []*RelayConnection {
return lo.Filter(lo.Values(connections),
func(e *RelayConnection, _ int) bool {
// Get valid connections
return e.Relay != nil
})
}
// StartAllRelayServers
// Connect to all relay servers.
func StartAllRelayServers(urls []string) {
for _, url := range urls {
StartRelayServer(url)
}
}
// StartRelayServer
// Connect to relay server.
func StartRelayServer(url string) {
c := &RelayConnection{
URL: url, WaitSpan: 1,
Error: make(chan error),
}
connections[url] = c
go func() {
for {
err := ConnectRelay(c)
if err != nil {
PrintConnectionError(c, err)
SleepTimeSpan(c)
continue
}
// Print connection succeeded
fmt.Printf("> connection success: %s\n", c.URL)
select {
// Reset when error occurs
case err = <-c.Error:
ClearRelay(c)
PrintConnectionError(c, err)
SleepTimeSpan(c)
}
}
}()
}
func ConnectRelay(c *RelayConnection) error {
ctx, cancel := context.WithCancel(context.Background())
relay, err := nostr.RelayConnect(ctx, c.URL)
if err != nil {
cancel()
return err
}
c.Relay = relay
c.Context = &ctx
c.Cancel = &cancel
return nil
}
func ClearRelay(c *RelayConnection) {
c.Relay = nil
c.Context = nil
c.Cancel = nil
}
func SleepTimeSpan(c *RelayConnection) {
// Insert Timespan to wait
time.Sleep(c.WaitSpan * time.Second)
c.WaitSpan = c.WaitSpan * 2
if c.WaitSpan > 60 {
c.WaitSpan = 60
}
}
func PrintConnectionError(c *RelayConnection, err error) {
fmt.Printf("> connection error: %s\n", c.URL)
fmt.Printf(">> error: %s\n", err)
}
// QuerySyncSemaphores
var sm = semaphore.NewWeighted(20)
// QuerySyncAll
// Query all relay servers and retrieve results synchronously
func QuerySyncAll(
ctx context.Context,
filters nostr.Filters,
) []*nostr.Event {
return QuerySyncAllWithOptions(
ctx, filters, DefaultQueryOptions(),
)
}
// QuerySyncAllWithOptions
// Query all relay servers and retrieve results synchronously
func QuerySyncAllWithOptions(
ctx context.Context,
filters nostr.Filters,
options QueryOptions,
) []*nostr.Event {
// Acquire semaphore
defer sm.Release(1)
err := sm.Acquire(ctx, 1)
if err != nil {
fmt.Println(err)
return nil
}
// Show query
var sb strings.Builder
sb.WriteString(filters.String() + "\n")
cs := GetConnections()
var endStreamCounter int32 = 0
var eoseStreamCounter int32 = 0
channel := make(chan *nostr.Event)
stop := make(chan interface{})
events := make([]*nostr.Event, 0)
dones := make([]chan interface{}, 0)
// Channel close mutex
var mu sync.Mutex
var wg sync.WaitGroup
var isStopped = false
var timeout = options.TimeoutSeconds * time.Second
// Stop all stream
closeAllStream := func() {
if !isStopped {
isStopped = true
close(stop)
// Send done signal to connections
for _, done := range dones {
close(done)
}
}
}
// Channel close processing
afterChannelClose := func() {
// Close channel if all subscriptions closed
atomic.AddInt32(&endStreamCounter, 1)
mu.Lock()
defer mu.Unlock()
// Close channel if all stream ended
if endStreamCounter == int32(len(cs)) {
closeAllStream()
return
}
if options.ExpectedEOSECount > 0 {
// Early termination (enough EOSE streaming count)
if eoseStreamCounter >= int32(options.ExpectedEOSECount) {
if len(events) > 0 || !options.RequiredOneEvent {
closeAllStream()
return
}
}
}
}
for _, c := range cs {
wg.Add(1)
// Timeout occurs if acquisition is not possible
ctx, cancel := context.WithTimeout(ctx, timeout)
sub, err := c.Relay.Subscribe(ctx, filters)
if err != nil {
go afterChannelClose()
c.Error <- err
wg.Done()
cancel()
continue
}
done := make(chan interface{})
dones = append(dones, done)
tUrl := c.URL
start := time.Now()
go func(
done <-chan interface{},
nsub *nostr.Subscription,
) {
defer func() {
afterChannelClose()
nsub.Unsub()
wg.Done()
cancel()
}()
for {
select {
// Termination process first
// End of Contents (Real All)
case <-nsub.EndOfStoredEvents:
sb.WriteString(">>> " + tUrl + " >> EndOfStoredEvents\n")
sb.WriteString(">>> spend (msec):" + strconv.Itoa(int(time.Now().UnixMilli()-start.UnixMilli())) + "\n")
atomic.AddInt32(&eoseStreamCounter, 1)
return
// Context Canceled
case <-ctx.Done():
sb.WriteString(">>> " + tUrl + " >> context.DONE\n")
sb.WriteString(">>> spend (msec):" + strconv.Itoa(int(time.Now().UnixMilli()-start.UnixMilli())) + "\n")
return
// Force Termination
case <-done:
sb.WriteString(">>> " + tUrl + " >> done\n")
sb.WriteString(">>> spend (msec):" + strconv.Itoa(int(time.Now().UnixMilli()-start.UnixMilli())) + "\n")
return
case ev := <-nsub.Events:
channel <- ev
continue
}
}
}(done, sub)
}
loop:
for {
select {
case <-stop:
break loop
case ev := <-channel:
events = append(events, ev)
mu.Lock()
if options.ExpectedEventCount > 0 {
// Early termination (got expected data)
if len(events) >= options.ExpectedEventCount {
closeAllStream()
mu.Unlock()
break loop
}
}
mu.Unlock()
continue
}
}
wg.Wait()
println(sb.String())
return events
}
// SentEventAll
func SentEventAll(
ctx context.Context,
event nostr.Event,
) bool {
cs := GetConnections()
var channelCounter int32 = 0
var successCounter int32 = 0
channel := make(chan nostr.Status)
stop := make(chan interface{})
// Channel close mutex
var mu sync.Mutex
var isStopped = false
afterChannelClose := func() {
// Close channel if all subscriptions closed
atomic.AddInt32(&channelCounter, 1)
mu.Lock()
if channelCounter == int32(len(cs)) {
if !isStopped {
isStopped = true
close(stop)
}
}
mu.Unlock()
}
// Publish events to all servers
for _, c := range cs {
go func(c *RelayConnection) {
status, err := c.Relay.Publish(ctx, event)
channel <- status
if err != nil {
c.Error <- err
}
afterChannelClose()
}(c)
}
loop:
for {
select {
case <-stop:
break loop
case status := <-channel:
// Increment success counter if sends succeeded
if status == nostr.PublishStatusSucceeded {
successCounter++
}
}
}
// Mark success under following condition
return successCounter >= (channelCounter / 2)
}