cmd/storj-sim: ensure prefix writer can be used concurrently (#2243)

This commit is contained in:
Egon Elbre 2019-06-19 22:30:48 +03:00 committed by GitHub
parent 402902563e
commit 35e71e5f95
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 47 additions and 1 deletions

View File

@ -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 {

View 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
})
}