Skip to content

Commit

Permalink
fix(network): lock updates
Browse files Browse the repository at this point in the history
Signed-off-by: Godefroy Ponsinet <godefroy.ponsinet@outlook.com>
  • Loading branch information
90dy committed Mar 12, 2019
1 parent 7193550 commit 1a8ffbb
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions core/network/network.go
Expand Up @@ -2,6 +2,7 @@ package network

import (
"context"
"sync"
"time"

"berty.tech/core/entity"
Expand All @@ -19,6 +20,8 @@ type Network struct {

handler func(context.Context, *entity.Envelope) (*entity.Void, error)

updating *sync.Mutex

shutdown context.CancelFunc
}

Expand All @@ -44,6 +47,7 @@ func New(ctx context.Context, opts ...config.Option) (*Network, error) {

net := &Network{
config: &config.Config{},
updating: &sync.Mutex{},
shutdown: cancel,
}

Expand Down Expand Up @@ -82,6 +86,27 @@ func New(ctx context.Context, opts ...config.Option) (*Network, error) {
return net, nil
}

// Update create new network and permit to override previous config
func (net *Network) Update(ctx context.Context, opts ...config.Option) error {
net.updating.Lock()
defer net.updating.Unlock()

updated, err := New(ctx, append([]config.Option{WithConfig(net.config)}, opts...)...)
if err != nil {
return errors.Wrap(err, "cannot update network: abort")
}

swap := *net

*net = *updated

net.updating = swap.updating

(&swap).Close(ctx)

return nil
}

func (net *Network) Close(ctx context.Context) error {
tracer := tracing.EnterFunc(ctx)
defer tracer.Finish()
Expand All @@ -101,15 +126,3 @@ func (net *Network) Close(ctx context.Context) error {

return nil
}

// Update create new network and permit to override previous config
func (net *Network) Update(ctx context.Context, opts ...config.Option) error {
updated, err := New(ctx, append([]config.Option{WithConfig(net.config)}, opts...)...)
if err != nil {
return errors.Wrap(err, "cannot update network: abort")
}
swap := *net
*net = *updated
(&swap).Close(ctx)
return nil
}

0 comments on commit 1a8ffbb

Please sign in to comment.