-
Notifications
You must be signed in to change notification settings - Fork 6
/
chunk.go
73 lines (66 loc) · 1.8 KB
/
chunk.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
73
package main
import (
"io/ioutil"
"path/filepath"
"sort"
"time"
)
// ChunkedHistoryReader reads Slack history json into a chunk.
// Reading whole history may eventually malloc all computer storage.
// Keep in mind that chunks should be garbage-collectable after use.
type ChunkedHistoryReader struct {
ChunkSize int
ChannelDirectory string
messageChannel chan Message
}
func NewChunkedHistoryReader(chunkSize int, channelDirectory string) *ChunkedHistoryReader {
r := new(ChunkedHistoryReader)
r.ChunkSize = chunkSize
r.ChannelDirectory = channelDirectory
r.messageChannel = make(chan Message, chunkSize)
go r.startReading()
return r
}
func (r *ChunkedHistoryReader) startReading() {
fileInfos, _ := ioutil.ReadDir(r.ChannelDirectory)
fileNames := make([]string, len(fileInfos))
for _, fi := range fileInfos {
fileNames = append(fileNames, fi.Name())
}
sort.Strings(fileNames)
for _, f := range fileNames {
messageSlice := ReadHistory(filepath.Join(r.ChannelDirectory, f))
for _, m := range messageSlice {
r.messageChannel <- m
}
}
close(r.messageChannel)
}
func (r *ChunkedHistoryReader) NextChunk() []Message {
messages := make([]Message, 0, r.ChunkSize)
for i := 0; i < r.ChunkSize; i++ {
m, ok := <-r.messageChannel
if ok {
messages = append(messages, m)
} else {
break
}
}
return messages
}
// ChunkInfo contains information about a chunk.
// It does not contain messages and its memory usage is O(1).
type ChunkInfo struct {
ChannelName string
NumMessages int
Start time.Time
End time.Time
}
func ToChunkInfo(channelName string, chunk []Message) ChunkInfo {
info := new(ChunkInfo)
info.ChannelName = channelName
info.NumMessages = len(chunk)
info.Start = SlackTsToTime(chunk[0].Ts)
info.End = SlackTsToTime(chunk[len(chunk)-1].Ts)
return *info
}