1
0
mirror of https://github.com/woodpecker-ci/woodpecker.git synced 2024-12-12 08:23:48 +02:00
woodpecker/stream/stream_impl.go

73 lines
1.4 KiB
Go
Raw Normal View History

2016-04-13 02:27:24 +02:00
package stream
import (
2016-04-23 02:35:32 +02:00
"fmt"
2016-04-13 02:27:24 +02:00
"io"
"sync"
)
2016-04-23 02:35:32 +02:00
type stream struct {
sync.Mutex
writers map[string]*writer
2016-04-13 02:27:24 +02:00
}
2016-04-23 02:35:32 +02:00
// New returns a new in-memory implementation of Stream.
func New() Stream {
return &stream{
writers: map[string]*writer{},
2016-04-13 02:27:24 +02:00
}
}
2016-04-23 02:35:32 +02:00
// Reader returns an io.Reader for reading from to the stream.
func (s *stream) Reader(name string) (io.ReadCloser, error) {
2016-04-23 02:35:32 +02:00
s.Lock()
defer s.Unlock()
2016-04-13 02:27:24 +02:00
2016-04-23 02:35:32 +02:00
if !s.exists(name) {
return nil, fmt.Errorf("stream: cannot read stream %s, not found", name)
2016-04-13 02:27:24 +02:00
}
2016-04-23 02:35:32 +02:00
return s.writers[name].Reader()
2016-04-13 02:27:24 +02:00
}
2016-04-23 02:35:32 +02:00
// Writer returns an io.WriteCloser for writing to the stream.
func (s *stream) Writer(name string) (io.WriteCloser, error) {
s.Lock()
defer s.Unlock()
2016-04-13 02:27:24 +02:00
2016-04-23 02:35:32 +02:00
if !s.exists(name) {
return nil, fmt.Errorf("stream: cannot write stream %s, not found", name)
}
return s.writers[name], nil
2016-04-13 02:27:24 +02:00
}
2016-04-23 02:35:32 +02:00
// Create creates a new stream.
func (s *stream) Create(name string) error {
s.Lock()
defer s.Unlock()
if s.exists(name) {
return fmt.Errorf("stream: cannot create stream %s, already exists", name)
}
2016-04-13 02:27:24 +02:00
2016-04-23 02:35:32 +02:00
s.writers[name] = newWriter()
2016-04-13 02:27:24 +02:00
return nil
}
2016-04-23 02:35:32 +02:00
// Delete deletes the stream by key.
func (s *stream) Delete(name string) error {
s.Lock()
defer s.Unlock()
if !s.exists(name) {
return fmt.Errorf("stream: cannot delete stream %s, not found", name)
}
2016-04-23 02:50:28 +02:00
w := s.writers[name]
2016-04-23 02:35:32 +02:00
delete(s.writers, name)
2016-04-23 02:50:28 +02:00
return w.Close()
2016-04-13 02:27:24 +02:00
}
2016-04-23 02:35:32 +02:00
func (s *stream) exists(name string) bool {
_, exists := s.writers[name]
return exists
2016-04-13 02:27:24 +02:00
}