Debian Codegraph @

pipe.go

raw symbols SCIP
1 package csv
2
3 // Implements a unidirectional channel that can connect a reader process to a writer process.
4 type Pipe interface {
5 Builder() WriterBuilder // Builds a Writer for the write end of the pipe
6 Reader() Reader // Returns the Reader for the read end of the pipe
7 }
8
9 type pipe struct {
10 header []string
11 ch chan Record
12 init chan interface{}
13 err error
14 }
15
16 type pipeWriter struct {
17 pipe *pipe
18 builder RecordBuilder
19 }
20
21 // Answer a new Pipe whose Builder and Reader can be used to connect two chained
22 // processes.
23 func NewPipe() Pipe {
24 return &pipe{
25 ch: make(chan Record),
26 err: nil,
27 init: make(chan interface{}),
28 }
29 }
30
31 func (p *pipe) Reader() Reader {
32 return p
33 }
34
35 func (p *pipe) C() <-chan Record {
36 <-p.init
37 return p.ch
38 }
39
40 func (p *pipe) Close() {
41 }
42
43 func (p *pipe) Header() []string {
44 <-p.init
45 return p.header
46 }
47
48 func (p *pipe) Error() error {
49 <-p.init
50 return p.err
51 }
52
53 func (p *pipe) Builder() WriterBuilder {
54 return func(header []string) Writer {
55 p.header = header
56 close(p.init)
57 return &pipeWriter{pipe: p, builder: NewRecordBuilder(header)}
58 }
59 }
60
61 func (p *pipeWriter) Blank() Record {
62 return p.builder(make([]string, len(p.pipe.header)))
63 }
64
65 func (p *pipeWriter) Close(err error) error {
66 p.pipe.err = err
67 close(p.pipe.ch)
68 return nil
69 }
70
71 func (p *pipeWriter) Error() error {
72 return p.pipe.err
73 }
74
75 func (p *pipeWriter) Header() []string {
76 return p.pipe.header
77 }
78
79 func (p *pipeWriter) Write(r Record) error {
80 p.pipe.ch <- r
81 return nil
82 }
83
84 // A pipeline of processes.
85 type pipeline struct {
86 stages []Process
87 }
88
89 // Join a sequence of processes by connecting them with pipes, returning a new process that
90 // represents the entire pipeline.
91 func NewPipeLine(p []Process) Process {
92 if p == nil || len(p) == 0 {
93 p = []Process{&CatProcess{}}
94 }
95 return &pipeline{
96 stages: p,
97 }
98 }
99
100 // Run the pipeline by connecting each stage with pipes and then running each stage
101 // as a goroutine.
102 func (p *pipeline) Run(r Reader, b WriterBuilder, errCh chan<- error) {
103 errCh <- func() (err error) {
104
105 errors := make(chan error, len(p.stages))
106 for _, c := range p.stages[:len(p.stages)-1] {
107 p := NewPipe()
108 go c.Run(r, p.Builder(), errors)
109 r = p.Reader()
110 }
111 go p.stages[len(p.stages)-1].Run(r, b, errors)
112
113 running := len(p.stages)
114
115 for running > 0 {
116 e := <-errors
117 running--
118 if err == nil {
119 err = e
120 }
121 }
122
123 return err
124 }()
125 }