cmd/storj-sim: ensure prefix writer can be used concurrently (#2243)
This commit is contained in:
parent
402902563e
commit
35e71e5f95
@ -44,6 +44,8 @@ func NewPrefixWriter(defaultPrefix string, dst io.Writer) *PrefixWriter {
|
||||
type prefixWriter struct {
|
||||
*PrefixWriter
|
||||
prefix string
|
||||
|
||||
local sync.Mutex
|
||||
id string
|
||||
buffer []byte
|
||||
}
|
||||
@ -54,7 +56,12 @@ func (writer *PrefixWriter) Prefixed(prefix string) io.Writer {
|
||||
writer.prefixlen = max(writer.prefixlen, len(prefix))
|
||||
writer.mu.Unlock()
|
||||
|
||||
return &prefixWriter{writer, prefix, "", make([]byte, 0, writer.maxline)}
|
||||
return &prefixWriter{
|
||||
PrefixWriter: writer,
|
||||
prefix: prefix,
|
||||
id: "",
|
||||
buffer: make([]byte, 0, writer.maxline),
|
||||
}
|
||||
}
|
||||
|
||||
// Write implements io.Writer that prefixes lines.
|
||||
@ -68,6 +75,9 @@ func (writer *prefixWriter) Write(data []byte) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
writer.local.Lock()
|
||||
defer writer.local.Unlock()
|
||||
|
||||
var newID string
|
||||
if writer.id == "" {
|
||||
if start := bytes.Index(data, []byte("Node ")); start > 0 {
|
||||
|
36
cmd/storj-sim/prefix_test.go
Normal file
36
cmd/storj-sim/prefix_test.go
Normal file
@ -0,0 +1,36 @@
|
||||
// Copyright (C) 2019 Storj Labs, Inc.
|
||||
// See LICENSE for copying information.
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
func TestPrefixWriter(t *testing.T) {
|
||||
root := NewPrefixWriter("", ioutil.Discard)
|
||||
alpha := root.Prefixed("alpha")
|
||||
beta := root.Prefixed("beta")
|
||||
|
||||
var group errgroup.Group
|
||||
defer func() {
|
||||
require.NoError(t, group.Wait())
|
||||
}()
|
||||
|
||||
group.Go(func() error {
|
||||
_, err := alpha.Write([]byte{1, 2, 3})
|
||||
return err
|
||||
})
|
||||
group.Go(func() error {
|
||||
_, err := alpha.Write([]byte{3, 2, 1})
|
||||
return err
|
||||
})
|
||||
group.Go(func() error {
|
||||
_, err := beta.Write([]byte{1, 2, 3})
|
||||
return err
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue
Block a user