forked from anyproto/go-threads
-
Notifications
You must be signed in to change notification settings - Fork 0
/
threads.go
394 lines (348 loc) · 9.88 KB
/
threads.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
383
384
385
386
387
388
389
390
391
392
393
394
package threads
import (
"context"
"fmt"
"io"
bserv "github.com/ipfs/go-blockservice"
"github.com/ipfs/go-cid"
format "github.com/ipfs/go-ipld-format"
logging "github.com/ipfs/go-log"
ic "github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/protocol"
gostream "github.com/libp2p/go-libp2p-gostream"
ma "github.com/multiformats/go-multiaddr"
"github.com/textileio/go-textile-core/crypto"
"github.com/textileio/go-textile-core/thread"
tserv "github.com/textileio/go-textile-core/threadservice"
tstore "github.com/textileio/go-textile-core/threadstore"
"github.com/textileio/go-textile-threads/cbor"
pb "github.com/textileio/go-textile-threads/pb"
"github.com/textileio/go-textile-threads/util"
logger "github.com/whyrusleeping/go-logging"
"google.golang.org/grpc"
)
var log = logging.Logger("threads")
const (
// IPEL is the protocol slug.
IPEL = "ipel"
// IPELCode is the protocol code.
IPELCode = 406
// IPELVersion is the current protocol version.
IPELVersion = "0.0.1"
// IPELProtocol is the threads protocol tag.
IPELProtocol protocol.ID = "/" + IPEL + "/" + IPELVersion
)
var addrProtocol = ma.Protocol{
Name: IPEL,
Code: IPELCode,
VCode: ma.CodeToVarint(IPELCode),
Size: ma.LengthPrefixedVarSize,
Transcoder: ma.TranscoderP2P,
}
func init() {
if err := ma.AddProtocol(addrProtocol); err != nil {
panic(err)
}
}
// MaxPullLimit is the maximum page size for pulling records.
var MaxPullLimit = 10000
// threads is an implementation of Threadservice.
type threads struct {
host host.Host
blocks bserv.BlockService
service *service
dagService format.DAGService
ctx context.Context
cancel context.CancelFunc
tstore.Threadstore
}
// NewThreads creates an instance of threads from the given host and thread store.
func NewThreads(ctx context.Context, h host.Host, bs bserv.BlockService, ds format.DAGService, ts tstore.Threadstore, debug bool) (tserv.Threadservice, error) {
var err error
if debug {
err = setLogLevels(map[string]logger.Level{
"threads": logger.DEBUG,
"threadstore": logger.DEBUG,
}, true)
if err != nil {
return nil, err
}
}
ctx, cancel := context.WithCancel(ctx)
t := &threads{
host: h,
blocks: bs,
dagService: ds,
ctx: ctx,
cancel: cancel,
Threadstore: ts,
}
t.service, err = newService(t)
if err != nil {
return nil, err
}
listener, err := gostream.Listen(h, IPELProtocol)
if err != nil {
return nil, err
}
rpc := grpc.NewServer()
go rpc.Serve(listener)
pb.RegisterThreadsServer(rpc, t.service)
return t, nil
}
// Close the threads instance.
func (t *threads) Close() (err error) {
var errs []error
weakClose := func(name string, c interface{}) {
if cl, ok := c.(io.Closer); ok {
if err = cl.Close(); err != nil {
errs = append(errs, fmt.Errorf("%s error: %s", name, err))
}
}
}
//weakClose("host", t.host) @todo: fix panic on close
weakClose("dagservice", t.dagService)
weakClose("threadstore", t.Threadstore)
if len(errs) > 0 {
return fmt.Errorf("failed while closing threads; err(s): %q", errs)
}
t.cancel()
return nil
}
// Host returns the underlying libp2p host.
func (t *threads) Host() host.Host {
return t.host
}
// DAGService returns the underlying dag service.
func (t *threads) DAGService() format.DAGService {
return t.dagService
}
// Add a new record by wrapping body. See AddOption for more.
func (t *threads) Add(ctx context.Context, body format.Node, opts ...tserv.AddOption) (l peer.ID, r thread.Record, err error) {
// Get or create a log for the new node
settings := tserv.AddOptions(opts...)
lg, err := t.getOrCreateOwnLog(settings.Thread)
if err != nil {
return
}
// Write a node locally
coded, err := t.createRecord(ctx, body, lg, settings)
if err != nil {
return
}
// Push out the new record
err = t.service.push(ctx, coded, settings.Thread, lg.ID, settings)
if err != nil {
return
}
return lg.ID, coded, nil
}
// Put an existing record. See PutOption for more.
func (t *threads) Put(ctx context.Context, rec thread.Record, opts ...tserv.PutOption) error {
// Get or create a log for the new rec
settings := tserv.PutOptions(opts...)
lg, err := t.getOrCreateLog(settings.Thread, settings.Log)
if err != nil {
return err
}
// Save the record locally
// Note: These get methods will return cached nodes.
block, err := rec.GetBlock(ctx, t.dagService)
if err != nil {
return err
}
event, ok := block.(*cbor.Event)
if !ok {
return fmt.Errorf("invalid event")
}
header, err := event.GetHeader(ctx, t.dagService, nil)
if err != nil {
return err
}
body, err := event.GetBody(ctx, t.dagService, nil)
if err != nil {
return err
}
err = t.dagService.AddMany(ctx, []format.Node{rec, event, header, body})
if err != nil {
return err
}
// Update head
t.SetHead(settings.Thread, lg.ID, rec.Cid())
return nil
}
// Pull for new records from the given log. See PullOption for more.
// Local results are returned if the log is owned by this host.
// Otherwise, records are pulled from the network at the log's addresses.
func (t *threads) Pull(ctx context.Context, id thread.ID, lid peer.ID, offset cid.Cid, opts ...tserv.PullOption) ([]thread.Record, error) {
settings := tserv.PullOptions(opts...)
if t.PubKey(id, lid) == nil {
return nil, fmt.Errorf("could not find log")
}
if t.PrivKey(id, lid) != nil { // This is our own log
return t.pullLocal(ctx, id, lid, offset, settings.Limit)
}
// Pull from addresses
return t.service.pull(ctx, id, lid, offset, settings)
}
// Logs returns info about the logs in the given thread.
func (t *threads) Logs(id thread.ID) []thread.LogInfo {
lgs := make([]thread.LogInfo, 0)
for _, lid := range t.ThreadInfo(id).Logs {
lg := t.LogInfo(id, lid)
lgs = append(lgs, lg)
}
return lgs
}
// Delete the given thread.
func (t *threads) Delete(ctx context.Context, id thread.ID) error {
panic("implement me")
}
// getPrivKey returns the host's private key.
func (t *threads) getPrivKey() ic.PrivKey {
return t.host.Peerstore().PrivKey(t.host.ID())
}
// createLog call util.CreateLog.
func (t *threads) createLog() (info thread.LogInfo, err error) {
return util.CreateLog(t.host.ID())
}
// getOrCreateLog returns the log with the given thread and log id
// If no log exists, a new one is created under the given thread.
func (t *threads) getOrCreateLog(id thread.ID, lid peer.ID) (info thread.LogInfo, err error) {
info = t.LogInfo(id, lid)
if info.PubKey != nil {
return
}
info, err = t.createLog()
if err != nil {
return
}
err = t.AddLog(id, info)
return
}
// getOwnLoad returns the log owned by the host under the given thread.
func (t *threads) getOwnLog(id thread.ID) (info thread.LogInfo) {
for _, lid := range t.LogsWithKeys(id) {
if t.PrivKey(id, lid) != nil {
info = t.LogInfo(id, lid)
return
}
}
return
}
// getOrCreateOwnLoad returns the log owned by the host under the given thread.
// If no log exists, a new one is created under the given thread.
func (t *threads) getOrCreateOwnLog(id thread.ID) (info thread.LogInfo, err error) {
info = t.getOwnLog(id)
if info.PubKey != nil {
return
}
info, err = t.createLog()
if err != nil {
return
}
err = t.AddLog(id, info)
return
}
// createRecord creates a new record with the given body as a new event body.
func (t *threads) createRecord(ctx context.Context, body format.Node, lg thread.LogInfo, settings *tserv.AddSettings) (thread.Record, error) {
if settings.Key == nil {
var key []byte
logKey := t.ReadKey(settings.Thread, settings.KeyLog)
if logKey != nil {
key = logKey
} else {
key = lg.ReadKey
}
var err error
settings.Key, err = crypto.ParseEncryptionKey(key)
if err != nil {
return nil, err
}
}
event, err := cbor.NewEvent(ctx, t.dagService, body, settings)
if err != nil {
return nil, err
}
prev := cid.Undef
if len(lg.Heads) != 0 {
prev = lg.Heads[0]
}
fk, err := crypto.ParseEncryptionKey(lg.FollowKey)
if err != nil {
return nil, err
}
rec, err := cbor.NewRecord(ctx, t.dagService, event, prev, lg.PrivKey, fk)
if err != nil {
return nil, err
}
t.SetHead(settings.Thread, lg.ID, rec.Cid())
return rec, nil
}
// pullLocal returns local records from the given thread that are ahead of
// offset but not farther than limit.
// It is possible to reach limit before offset, meaning that the caller
// will be responsible for the remaining traversal.
func (t *threads) pullLocal(ctx context.Context, id thread.ID, lid peer.ID, offset cid.Cid, limit int) ([]thread.Record, error) {
lg := t.LogInfo(id, lid)
if lg.PubKey == nil {
return nil, fmt.Errorf("could not find log")
}
fk, err := crypto.ParseDecryptionKey(lg.FollowKey)
if err != nil {
return nil, err
}
var recs []thread.Record
if limit <= 0 {
return recs, nil
}
if len(lg.Heads) != 1 {
return nil, fmt.Errorf("log head must reference exactly one node")
}
cursor := lg.Heads[0]
for {
if cursor.String() == offset.String() {
break
}
r, err := cbor.GetRecord(ctx, t.dagService, cursor, fk)
if err != nil {
return nil, err
}
recs = append([]thread.Record{r}, recs...)
if len(recs) >= MaxPullLimit {
break
}
cursor = r.PrevID()
}
return recs, nil
}
// setLogLevels sets the logging levels of the given log systems.
// color controls whether or not color codes are included in the output.
func setLogLevels(systems map[string]logger.Level, color bool) error {
var form string
if color {
form = logging.LogFormats["color"]
} else {
form = logging.LogFormats["nocolor"]
}
logger.SetFormatter(logger.MustStringFormatter(form))
logging.SetAllLoggers(logger.ERROR)
var err error
for sys, level := range systems {
if sys == "*" {
for _, s := range logging.GetSubsystems() {
err = logging.SetLogLevel(s, level.String())
if err != nil {
return err
}
}
}
err = logging.SetLogLevel(sys, level.String())
if err != nil {
return err
}
}
return nil
}