From 1a8ffbb42b7d2af6e382ba02437a499898181831 Mon Sep 17 00:00:00 2001 From: Godefroy Ponsinet Date: Tue, 12 Mar 2019 12:57:11 +0100 Subject: [PATCH] fix(network): lock updates Signed-off-by: Godefroy Ponsinet --- core/network/network.go | 37 +++++++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/core/network/network.go b/core/network/network.go index a248e540e8..841f638d75 100644 --- a/core/network/network.go +++ b/core/network/network.go @@ -2,6 +2,7 @@ package network import ( "context" + "sync" "time" "berty.tech/core/entity" @@ -19,6 +20,8 @@ type Network struct { handler func(context.Context, *entity.Envelope) (*entity.Void, error) + updating *sync.Mutex + shutdown context.CancelFunc } @@ -44,6 +47,7 @@ func New(ctx context.Context, opts ...config.Option) (*Network, error) { net := &Network{ config: &config.Config{}, + updating: &sync.Mutex{}, shutdown: cancel, } @@ -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() @@ -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 -}