This repository has been archived by the owner on Oct 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 215
/
reader.go
72 lines (64 loc) · 1.55 KB
/
reader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package file
import (
"encoding/json"
"io"
"github.com/compose/transporter/client"
"github.com/compose/transporter/log"
"github.com/compose/transporter/message"
"github.com/compose/transporter/message/data"
"github.com/compose/transporter/message/ops"
)
var (
_ client.Reader = &Reader{}
)
// Reader implements the behavior defined by client.Reader for interfacing with the file.
type Reader struct{}
func newReader() client.Reader {
return &Reader{}
}
func (r *Reader) Read(_ map[string]client.MessageSet, filterFn client.NsFilterFunc) client.MessageChanFunc {
return func(s client.Session, done chan struct{}) (chan client.MessageSet, error) {
out := make(chan client.MessageSet)
session := s.(*Session)
ns := session.file.Name()
go func() {
defer close(out)
results := r.decodeFile(session, done)
for {
select {
case <-done:
return
case result, ok := <-results:
if !ok {
log.With("file", ns).Infoln("Read completed")
return
}
if filterFn(ns) {
out <- client.MessageSet{
Msg: message.From(ops.Insert, ns, result),
}
}
}
}
}()
return out, nil
}
}
func (r *Reader) decodeFile(s *Session, done chan struct{}) chan data.Data {
out := make(chan data.Data)
go func() {
defer close(out)
dec := json.NewDecoder(s.file)
for {
var doc = make(data.Data)
if err := dec.Decode(&doc); err == io.EOF {
return
} else if err != nil {
log.With("file", s.file.Name()).Errorf("Can't unmarshal document (%v)", err)
continue
}
out <- doc
}
}()
return out
}