Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

threads: fetch all unknown records #132

Merged
merged 7 commits into from
Nov 28, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions cbor/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (

"github.com/ipfs/go-cid"
cbornode "github.com/ipfs/go-ipld-cbor"
"github.com/ipfs/go-ipld-format"
format "github.com/ipfs/go-ipld-format"
mh "github.com/multiformats/go-multihash"
"github.com/textileio/go-textile-core/crypto"
"github.com/textileio/go-textile-core/crypto/symmetric"
Expand Down Expand Up @@ -91,7 +91,7 @@ func GetEvent(ctx context.Context, dag format.DAGService, id cid.Cid) (thread.Ev
}

// EventFromNode decodes the given node into an event.
func EventFromNode(node format.Node) (thread.Event, error) {
func EventFromNode(node format.Node) (*Event, error) {
jsign marked this conversation as resolved.
Show resolved Hide resolved
obj := new(event)
err := cbornode.DecodeInto(node.RawData(), obj)
if err != nil {
Expand All @@ -104,7 +104,7 @@ func EventFromNode(node format.Node) (thread.Event, error) {
}

// EventFromRecord returns the event within the given node.
func EventFromRecord(ctx context.Context, dag format.DAGService, rec thread.Record) (thread.Event, error) {
func EventFromRecord(ctx context.Context, dag format.DAGService, rec thread.Record) (*Event, error) {
jsign marked this conversation as resolved.
Show resolved Hide resolved
block, err := rec.GetBlock(ctx, dag)
if err != nil {
return nil, err
Expand Down
9 changes: 6 additions & 3 deletions cbor/record.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import (
"fmt"

"github.com/ipfs/go-cid"
"github.com/ipfs/go-ipld-cbor"
"github.com/ipfs/go-ipld-format"
cbornode "github.com/ipfs/go-ipld-cbor"
format "github.com/ipfs/go-ipld-format"
ic "github.com/libp2p/go-libp2p-core/crypto"
mh "github.com/multiformats/go-multihash"
"github.com/textileio/go-textile-core/crypto"
Expand Down Expand Up @@ -101,10 +101,13 @@ func RecordToProto(ctx context.Context, dag format.DAGService, rec thread.Record
if err != nil {
return nil, err
}
event, err := EventFromNode(block)
event, ok := block.(*Event)
if !ok {
event, err = EventFromNode(block)
sanderpick marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return nil, err
}
}
header, err := event.GetHeader(ctx, dag, nil)
if err != nil {
return nil, err
Expand Down
2 changes: 1 addition & 1 deletion client.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import (

const (
// reqTimeout is the duration to wait for a request to complete.
reqTimeout = time.Second * 5
reqTimeout = time.Second * 10
jsign marked this conversation as resolved.
Show resolved Hide resolved
)

// getLogs in a thread.
Expand Down
9 changes: 8 additions & 1 deletion eventstore/storethread.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,14 @@ func (a *singleThreadAdapter) threadToStore(wg *sync.WaitGroup) {

event, err := threadcbor.EventFromRecord(ctx, a.api, rec.Value())
if err != nil {
log.Fatalf("error when getting event from record: %v", err) // ToDo: Buffer them and retry...
block, err := rec.Value().GetBlock(ctx, a.api)
if err != nil { // ToDo: Buffer them and retry...
log.Fatalf("error when getting block from record: %v", err)
}
event, err = threadcbor.EventFromNode(block)
if err != nil {
log.Fatalf("error when decoding block to event: %v", err)
}
sanderpick marked this conversation as resolved.
Show resolved Hide resolved
}

readKey, err := a.api.Store().ReadKey(a.threadID)
Expand Down
13 changes: 12 additions & 1 deletion service.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,19 @@ func (s *service) PushLog(ctx context.Context, req *pb.PushLogRequest) (*pb.Push
}

lg := logFromProto(req.Log)
if err := s.threads.store.AddLog(req.ThreadID.ID, lg); err != nil {
head, err := s.threads.store.Heads(req.ThreadID.ID, lg.ID)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
if head == nil {
if err := s.threads.store.AddLog(req.ThreadID.ID, lg); err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
}

go func() {
s.threads.pullLock.Lock()
defer s.threads.pullLock.Unlock()
// Get log records for this new log
recs, err := s.getRecords(
s.threads.ctx,
Expand Down Expand Up @@ -222,6 +230,9 @@ func (s *service) GetRecords(ctx context.Context, req *pb.GetRecordsRequest) (*p

// PushRecord receives a push record request.
func (s *service) PushRecord(ctx context.Context, req *pb.PushRecordRequest) (*pb.PushRecordReply, error) {
// ToDo: fix concurrency
s.threads.pullLock.Lock()
defer s.threads.pullLock.Unlock()
jsign marked this conversation as resolved.
Show resolved Hide resolved
if req.Header == nil {
return nil, status.Error(codes.FailedPrecondition, "request header is required")
}
Expand Down
119 changes: 76 additions & 43 deletions threads.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,14 @@ func (t *threads) Close() (err error) {
if len(errs) > 0 {
return fmt.Errorf("failed while closing threads; err(s): %q", errs)
}

t.pullLock.Lock()
defer t.pullLock.Unlock()
// Wait for all thread pulls to finish
for _, semaph := range t.pullLocks {
semaph <- struct{}{}
}
Comment on lines +191 to +196
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quite important thing that was missing.
On Close(), we should wait for all thread pulls that might be running before saying we're done.

This basically tries to get all 1 buffered channels (semaphores) of threads and basically wait to lock all of them. If that's the case, no thread pull is running.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clever!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, basically using a 1 buffered channel is almost the same as a mutex. The thing is that this way you can test for lock and dismiss if locked. (with a default case).

I'm not sure I explained this decision originally. In PullThread we want to try to pull the thread, but if it's already being pulled we want to dismiss and go on. You can't "try" a Lock() with a mutex, but you can with a channel.

Anyway, this will make more sense in the next PR when these semaphores are fully used (and delete the global lock). Did it now just not to forget and let the threadservice close when still are threads being pulled.


return nil
}

Expand Down Expand Up @@ -271,22 +279,24 @@ func (t *threads) AddThread(
return t.store.ThreadInfo(id)
}

// PullThread for new records.
// Logs owned by this host are traversed locally.
// Remotely addressed logs are pulled from the network.
func (t *threads) PullThread(ctx context.Context, id thread.ID) error {
log.Debugf("pulling thread %s...", id.String())
func (t *threads) getThreadSemaphore(id thread.ID) chan struct{} {
var ptl chan struct{}
var ok bool
// ToDo: fix concurrency
t.pullLock.Lock()
defer t.pullLock.Unlock()
if ptl, ok = t.pullLocks[id]; !ok {
ptl = make(chan struct{}, 1)
t.pullLocks[id] = ptl
}
// t.pullLock.Unlock()
return ptl
}
jsign marked this conversation as resolved.
Show resolved Hide resolved

// PullThread for new records.
// Logs owned by this host are traversed locally.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not related to this PR, but this comment must be outdated / relic from the old pull functionality.

// Remotely addressed logs are pulled from the network.
func (t *threads) PullThread(ctx context.Context, id thread.ID) error {
log.Debugf("pulling thread %s...", id.String())
ptl := t.getThreadSemaphore(id)
select {
case ptl <- struct{}{}:
lgs, err := t.getLogs(id)
Expand All @@ -310,6 +320,7 @@ func (t *threads) PullThread(ctx context.Context, id thread.ID) error {
}
wg := sync.WaitGroup{}
for _, lg := range lgs {
// (jsign): after fist iteration, offsets might not be correct anymore
wg.Add(1)
// ToDo: fix concurrency
func(lg thread.LogInfo) {
Expand Down Expand Up @@ -541,11 +552,24 @@ func (t *threads) Subscribe(opts ...options.SubOption) tserv.Subscription {

// putRecord adds an existing record. See PutOption for more.
func (t *threads) putRecord(ctx context.Context, id thread.ID, lid peer.ID, rec thread.Record) error {
jsign marked this conversation as resolved.
Show resolved Hide resolved
knownRecord, err := t.bstore.Has(rec.Cid())
if err != nil {
return err
unknownRecords := []thread.Record{}
cid := rec.Cid()
for cid.Defined() {
exist, err := t.bstore.Has(cid)
if err != nil {
return err
}
if exist {
break
}
r, err := t.GetRecord(ctx, id, cid)
if err != nil {
return err
}
unknownRecords = append(unknownRecords, r)
cid = r.PrevID()
}
if knownRecord {
jsign marked this conversation as resolved.
Show resolved Hide resolved
if len(unknownRecords) == 0 {
jsign marked this conversation as resolved.
Show resolved Hide resolved
return nil
}

Expand All @@ -555,42 +579,51 @@ func (t *threads) putRecord(ctx context.Context, id thread.ID, lid peer.ID, rec
return err
}

// Save the record locally
// Note: These get methods will return cached nodes.
block, err := rec.GetBlock(ctx, t)
if err != nil {
return err
}
event, ok := block.(*cbor.Event)
if !ok {
return fmt.Errorf("invalid event")
}
header, err := event.GetHeader(ctx, t, nil)
if err != nil {
return err
}
body, err := event.GetBody(ctx, t, nil)
if err != nil {
return err
}
err = t.AddMany(ctx, []format.Node{rec, event, header, body})
if err != nil {
return err
}
for i := len(unknownRecords) - 1; i >= 0; i-- {
jsign marked this conversation as resolved.
Show resolved Hide resolved
r := unknownRecords[i]
// Save the record locally
// Note: These get methods will return cached nodes.
block, err := r.GetBlock(ctx, t)
if err != nil {
return err
}
event, ok := block.(*cbor.Event)
if !ok {
event, err = cbor.EventFromNode(block)
if err != nil {
return fmt.Errorf("invalid event: %v", err)
}
sanderpick marked this conversation as resolved.
Show resolved Hide resolved
}
header, err := event.GetHeader(ctx, t, nil)
if err != nil {
return err
}
body, err := event.GetBody(ctx, t, nil)
if err != nil {
return err
}
err = t.AddMany(ctx, []format.Node{r, event, header, body})
if err != nil {
return err
}

log.Debugf("put record %s (thread=%s, log=%s)", r.Cid().String(), id, lg.ID)

// Notify local listeners
err = t.bus.SendWithTimeout(&record{
jsign marked this conversation as resolved.
Show resolved Hide resolved
Record: r,
threadID: id,
logID: lg.ID,
}, time.Second)
if err != nil {
return err
}
}
// Update head
if err = t.store.SetHead(id, lg.ID, rec.Cid()); err != nil {
if err = t.store.SetHead(id, lg.ID, unknownRecords[0].Cid()); err != nil {
jsign marked this conversation as resolved.
Show resolved Hide resolved
return err
}

log.Debugf("put record %s (thread=%s, log=%s)", rec.Cid().String(), id, lg.ID)

// Notify local listeners
return t.bus.SendWithTimeout(&record{
Record: rec,
threadID: id,
logID: lg.ID,
}, time.Second)
return nil
}

// getPrivKey returns the host's private key.
Expand Down