astraproxy/logwriter.go

58 lines
929 B
Go
Raw Normal View History

2020-05-19 21:53:13 +02:00
package main
import (
2021-02-26 08:09:55 +01:00
"errors"
"io"
"time"
2020-05-19 21:53:13 +02:00
)
const MAX_LOG_QLEN = 128
const QUEUE_SHUTDOWN_TIMEOUT = 500 * time.Millisecond
type LogWriter struct {
2021-02-26 08:09:55 +01:00
writer io.Writer
ch chan []byte
done chan struct{}
2020-05-19 21:53:13 +02:00
}
func (lw *LogWriter) Write(p []byte) (int, error) {
2021-02-26 08:09:55 +01:00
if p == nil {
return 0, errors.New("Can't write nil byte slice")
}
buf := make([]byte, len(p))
copy(buf, p)
select {
case lw.ch <- buf:
return len(p), nil
default:
return 0, errors.New("Writer queue overflow")
}
2020-05-19 21:53:13 +02:00
}
func NewLogWriter(writer io.Writer) *LogWriter {
2021-02-26 08:09:55 +01:00
lw := &LogWriter{writer,
make(chan []byte, MAX_LOG_QLEN),
make(chan struct{})}
go lw.loop()
return lw
2020-05-19 21:53:13 +02:00
}
func (lw *LogWriter) loop() {
2021-02-26 08:09:55 +01:00
for p := range lw.ch {
if p == nil {
break
}
lw.writer.Write(p)
}
lw.done <- struct{}{}
2020-05-19 21:53:13 +02:00
}
func (lw *LogWriter) Close() {
2021-02-26 08:09:55 +01:00
lw.ch <- nil
timer := time.After(QUEUE_SHUTDOWN_TIMEOUT)
select {
case <-timer:
case <-lw.done:
}
2020-05-19 21:53:13 +02:00
}