59 lines
1.1 KiB
Go
59 lines
1.1 KiB
Go
|
|
package subprocess
|
||
|
|
|
||
|
|
import (
|
||
|
|
"fmt"
|
||
|
|
"io"
|
||
|
|
"sync"
|
||
|
|
)
|
||
|
|
|
||
|
|
// boundedResultWriter preserves result bytes and reports failures to the process
|
||
|
|
// supervisor. Its target remains owned by the caller.
|
||
|
|
type boundedResultWriter struct {
|
||
|
|
target io.Writer
|
||
|
|
limit int64
|
||
|
|
owner string
|
||
|
|
abort chan<- error
|
||
|
|
written int64
|
||
|
|
mu sync.Mutex
|
||
|
|
err error
|
||
|
|
}
|
||
|
|
|
||
|
|
func (w *boundedResultWriter) Write(data []byte) (int, error) {
|
||
|
|
remaining := w.limit - w.written
|
||
|
|
if remaining < 0 {
|
||
|
|
remaining = 0
|
||
|
|
}
|
||
|
|
accepted := data
|
||
|
|
if int64(len(accepted)) > remaining {
|
||
|
|
accepted = accepted[:remaining]
|
||
|
|
}
|
||
|
|
n, err := w.target.Write(accepted)
|
||
|
|
w.written += int64(n)
|
||
|
|
if err == nil && n != len(accepted) {
|
||
|
|
err = io.ErrShortWrite
|
||
|
|
}
|
||
|
|
if err != nil {
|
||
|
|
err = fmt.Errorf("%s stdout result capture: %w", w.owner, err)
|
||
|
|
} else if len(accepted) != len(data) {
|
||
|
|
err = fmt.Errorf("stdout result capture for %s exceeded %d bytes", w.owner, w.limit)
|
||
|
|
}
|
||
|
|
if err != nil {
|
||
|
|
w.mu.Lock()
|
||
|
|
if w.err == nil {
|
||
|
|
w.err = err
|
||
|
|
select {
|
||
|
|
case w.abort <- err:
|
||
|
|
default:
|
||
|
|
}
|
||
|
|
}
|
||
|
|
w.mu.Unlock()
|
||
|
|
}
|
||
|
|
return n, err
|
||
|
|
}
|
||
|
|
|
||
|
|
func (w *boundedResultWriter) Err() error {
|
||
|
|
w.mu.Lock()
|
||
|
|
defer w.mu.Unlock()
|
||
|
|
return w.err
|
||
|
|
}
|