-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathexpiration.go
135 lines (112 loc) · 2.62 KB
/
expiration.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
package khatru
import (
"container/heap"
"context"
"sync"
"time"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip40"
)
type expiringEvent struct {
id string
expiresAt nostr.Timestamp
}
type expiringEventHeap []expiringEvent
func (h expiringEventHeap) Len() int { return len(h) }
func (h expiringEventHeap) Less(i, j int) bool { return h[i].expiresAt < h[j].expiresAt }
func (h expiringEventHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *expiringEventHeap) Push(x interface{}) {
*h = append(*h, x.(expiringEvent))
}
func (h *expiringEventHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
type expirationManager struct {
events expiringEventHeap
mu sync.Mutex
relay *Relay
interval time.Duration
initialScanDone bool
}
func newExpirationManager(relay *Relay) *expirationManager {
return &expirationManager{
events: make(expiringEventHeap, 0),
relay: relay,
interval: time.Hour,
}
}
func (em *expirationManager) start(ctx context.Context) {
ticker := time.NewTicker(em.interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if !em.initialScanDone {
em.initialScan(ctx)
em.initialScanDone = true
}
em.checkExpiredEvents(ctx)
}
}
}
func (em *expirationManager) initialScan(ctx context.Context) {
em.mu.Lock()
defer em.mu.Unlock()
// query all events
for _, query := range em.relay.QueryEvents {
ch, err := query(ctx, nostr.Filter{})
if err != nil {
continue
}
for evt := range ch {
if expiresAt := nip40.GetExpiration(evt.Tags); expiresAt != -1 {
heap.Push(&em.events, expiringEvent{
id: evt.ID,
expiresAt: expiresAt,
})
}
}
}
heap.Init(&em.events)
}
func (em *expirationManager) checkExpiredEvents(ctx context.Context) {
em.mu.Lock()
defer em.mu.Unlock()
now := nostr.Now()
// keep deleting events from the heap as long as they're expired
for em.events.Len() > 0 {
next := em.events[0]
if now < next.expiresAt {
break
}
heap.Pop(&em.events)
for _, query := range em.relay.QueryEvents {
ch, err := query(ctx, nostr.Filter{IDs: []string{next.id}})
if err != nil {
continue
}
if evt := <-ch; evt != nil {
for _, del := range em.relay.DeleteEvent {
del(ctx, evt)
}
}
break
}
}
}
func (em *expirationManager) trackEvent(evt *nostr.Event) {
if expiresAt := nip40.GetExpiration(evt.Tags); expiresAt != -1 {
em.mu.Lock()
heap.Push(&em.events, expiringEvent{
id: evt.ID,
expiresAt: expiresAt,
})
em.mu.Unlock()
}
}