1
0
mirror of https://github.com/woodpecker-ci/woodpecker.git synced 2025-01-29 18:04:15 +02:00
woodpecker/stream/stream_impl.go

73 lines
1.4 KiB
Go
Raw Normal View History

2016-04-12 17:27:24 -07:00
package stream
import (
2016-04-22 17:35:32 -07:00
"fmt"
2016-04-12 17:27:24 -07:00
"io"
"sync"
)
2016-04-22 17:35:32 -07:00
type stream struct {
sync.Mutex
writers map[string]*writer
2016-04-12 17:27:24 -07:00
}
2016-04-22 17:35:32 -07:00
// New returns a new in-memory implementation of Stream.
func New() Stream {
return &stream{
writers: map[string]*writer{},
2016-04-12 17:27:24 -07:00
}
}
2016-04-22 17:35:32 -07:00
// Reader returns an io.Reader for reading from to the stream.
func (s *stream) Reader(name string) (io.ReadCloser, error) {
2016-04-22 17:35:32 -07:00
s.Lock()
defer s.Unlock()
2016-04-12 17:27:24 -07:00
2016-04-22 17:35:32 -07:00
if !s.exists(name) {
return nil, fmt.Errorf("stream: cannot read stream %s, not found", name)
2016-04-12 17:27:24 -07:00
}
2016-04-22 17:35:32 -07:00
return s.writers[name].Reader()
2016-04-12 17:27:24 -07:00
}
2016-04-22 17:35:32 -07: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-12 17:27:24 -07:00
2016-04-22 17:35:32 -07:00
if !s.exists(name) {
return nil, fmt.Errorf("stream: cannot write stream %s, not found", name)
}
return s.writers[name], nil
2016-04-12 17:27:24 -07:00
}
2016-04-22 17:35:32 -07: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-12 17:27:24 -07:00
2016-04-22 17:35:32 -07:00
s.writers[name] = newWriter()
2016-04-12 17:27:24 -07:00
return nil
}
2016-04-22 17:35:32 -07: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-22 17:50:28 -07:00
w := s.writers[name]
2016-04-22 17:35:32 -07:00
delete(s.writers, name)
2016-04-22 17:50:28 -07:00
return w.Close()
2016-04-12 17:27:24 -07:00
}
2016-04-22 17:35:32 -07:00
func (s *stream) exists(name string) bool {
_, exists := s.writers[name]
return exists
2016-04-12 17:27:24 -07:00
}