forked from keks/go-orbitdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
orbitdb.go
103 lines (82 loc) · 2.07 KB
/
orbitdb.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 orbitdb is a Go implementation of https://github.com/haadcode/orbit-db.
package orbitdb
import (
"github.com/keks/go-ipfs-colog"
db "github.com/keks/go-ipfs-colog/immutabledb/ipfs-api"
"github.com/zacharyestep/go-orbitdb/handler"
"github.com/zacharyestep/go-orbitdb/pubsub"
ippubsub "github.com/zacharyestep/go-orbitdb/pubsub/ipfs-api"
"log"
"os"
)
// OrbitDB manages a colog and keeps it up-to-date using ipfs pubsub.
type OrbitDB struct {
topic string
logger *log.Logger
colog *colog.CoLog
pubsub pubsub.PubSub
}
// NewOrbitDB returns a new OrbitDB and subscribes to the given topic string.
func NewOrbitDB(topic string) (*OrbitDB, error) {
idb, err := db.New()
odb := &OrbitDB{
topic: topic,
logger: log.New(os.Stderr, "orbit.OrbitDB ", log.Ltime|log.Lshortfile),
colog: colog.New(idb),
pubsub: ippubsub.New(),
}
go odb.handleSubscription(topic)
return odb, err
}
// Add adds a given value to the database.
func (db *OrbitDB) Add(data interface{}) (*colog.Entry, error) {
e, err := db.colog.Add(data)
if err != nil {
return e, err
}
err = db.pubsub.Publish(db.topic, string(e.Hash))
return e, err
}
func (db *OrbitDB) handleSubscription(topic string) {
sub, err := db.pubsub.Subscribe(topic)
if err != nil {
db.logger.Println("subscribe error:", err, "; aborting")
return
}
defer sub.Cancel()
recCh := make(chan pubsub.Record)
errCh := make(chan error)
next := func() {
rec, err := sub.Next()
if err != nil {
errCh <- err
} else {
recCh <- rec
}
}
go next()
L:
for {
select {
case rec := <-recCh:
go next()
err := db.colog.FetchFromHead(colog.Hash(rec.Data()))
if err != nil {
db.logger.Println("fetch error:", err, "; continuing")
}
case err := <-errCh:
db.logger.Println("pubsub error:", err, "; cancelling")
break L
}
}
}
// Notify informs a handler about new colog Entries.
func (db *OrbitDB) Notify(h handler.Handler) {
for e := range db.colog.Watch() {
err := h.Handle(e)
if err != nil && err != handler.ErrWrongOp {
// ignore ErrWrongOp errors
db.logger.Println(err)
}
}
}