This repository has been archived by the owner on Jul 16, 2019. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subdb.go
103 lines (86 loc) · 2.21 KB
/
subdb.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
package main
import (
"encoding/json"
"strings"
"time"
"github.com/boltdb/bolt"
"github.com/emersion/go-ostatus/pubsubhubbub"
log "github.com/sirupsen/logrus"
)
var subscriptionsBucket = []byte("subscriptions")
type subscriptionData struct {
Secret string `json:"secret"`
LeaseEnd time.Time `json:"lease_end"`
}
func subscriptionToKey(topicURL, callbackURL string) []byte {
return []byte(topicURL + " " + callbackURL)
}
func keyToSubscription(k []byte) (topicURL, callbackURL string) {
parts := strings.SplitN(string(k), " ", 2)
if len(parts) == 2 {
return parts[0], parts[1]
}
return "", ""
}
func newSubscriptionDB(p *pubsubhubbub.Publisher, db *bolt.DB) error {
// Restore old subscriptions
if err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(subscriptionsBucket)
if b == nil {
return nil
}
return b.ForEach(func(k, v []byte) error {
topicURL, callbackURL := keyToSubscription(k)
s := new(subscriptionData)
if err := json.Unmarshal(v, s); err != nil {
return err
}
if s.LeaseEnd.Before(time.Now()) {
return b.Delete(k)
}
log.WithFields(log.Fields{
"topic": topicURL,
"callback": callbackURL,
"lease_end": s.LeaseEnd,
}).Debug("Re-registering subscription")
return p.Register(topicURL, callbackURL, s.Secret, s.LeaseEnd)
})
}); err != nil {
return err
}
// Save new subscriptions
p.SubscriptionState = func(topicURL, callbackURL, secret string, leaseEnd time.Time) {
le := log.WithFields(log.Fields{
"topic": topicURL,
"callback": callbackURL,
"lease_end": leaseEnd,
})
if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists(subscriptionsBucket)
if err != nil {
return err
}
k := subscriptionToKey(topicURL, callbackURL)
if !leaseEnd.IsZero() {
s := &subscriptionData{Secret: secret, LeaseEnd: leaseEnd}
v, err := json.Marshal(s)
if err != nil {
return err
}
if err := b.Put(k, v); err != nil {
return err
}
} else {
if err := b.Delete(k); err != nil {
return err
}
}
return nil
}); err != nil {
le.WithError(err).Error("Unable to save subscription")
return
}
le.Debug("Added new subscription")
}
return nil
}