/
scan.go
268 lines (258 loc) · 6.41 KB
/
scan.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
// Copyright 2023 Sneller, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package db
import (
"context"
"errors"
"fmt"
"io/fs"
"math"
"strings"
"time"
"github.com/SnellerInc/sneller/date"
"github.com/SnellerInc/sneller/fsutil"
"github.com/SnellerInc/sneller/ion/blockfmt"
)
var errStop = errors.New("stop walking")
// Scan performs an incremental append operation
// on a table by listing input objects and adding them
// to the index. Scan returns the number of objects
// added to the table or an error. If Scan returns (0, nil),
// then scanning has already completed and no further
// calls to Scan are necessary to build the table.
//
// Semantically, Scan performs a list operation and a call
// to c.Append on the listed items, taking care to list
// incrementally from the last call to Append.
func (c *Config) Scan(who Tenant, db, table string) (int, error) {
st, err := c.open(db, table, who)
if err != nil {
return 0, err
}
idx, err := st.index(context.Background())
if err != nil {
// if the index isn't present
// or is out-of-date, create a new one
if shouldRebuild(err) {
idx = &blockfmt.Index{
Name: table,
Algo: "zstd",
}
} else {
return 0, err
}
}
return st.scan(idx, true)
}
// defChanged returns whether st.def has changed
// since the index was built by comparing the
// hash of st.def against the hash in idx.
func (st *tableState) defChanged(idx *blockfmt.Index) bool {
d := idx.UserData.Field("definition").Field("hash")
if !d.IsBlob() {
return false
}
hash, _ := d.BlobShared()
return string(st.def.Hash()) != string(hash)
}
func (st *tableState) scan(idx *blockfmt.Index, flushOnComplete bool) (int, error) {
changed := st.defChanged(idx)
if changed {
flushOnComplete = true
}
if changed || len(idx.Cursors) != len(st.def.Inputs) {
idx.LastScan = date.Now()
idx.Cursors = make([]string, len(st.def.Inputs))
idx.Scanning = true
}
if !idx.Scanning {
return 0, nil
}
idx.Inputs.Backing = st.ofs
var ctx context.Context // set if needed
var c collector
err := c.init(st.def.Partitions)
if err != nil {
return 0, err
}
maxSize := st.conf.MaxScanBytes
if maxSize <= 0 {
maxSize = math.MaxInt64
}
maxInputs := st.conf.MaxScanObjects
if maxInputs <= 0 {
maxInputs = math.MaxInt
}
maxDuration := st.conf.MaxScanTime
if maxDuration <= 0 {
maxDuration = 15 * time.Second
}
total := 0
size := int64(0)
complete := true
ids := make(map[string]int)
nextID := idx.Objects()
start := time.Now()
for i := range st.def.Inputs {
if total >= maxInputs || size >= maxSize {
complete = false
break
}
fullpat := st.def.Inputs[i].Pattern
infs, pat, err := st.owner.Split(fullpat)
if err != nil {
// invalid definition?
return 0, err
}
format := st.def.Inputs[i].Format
seek := idx.Cursors[i]
prefix := infs.Prefix()
walkfs := fs.FS(infs)
if cfs, ok := infs.(ContextFS); ok {
if ctx == nil {
deadline := start.Add(maxDuration)
var cancel context.CancelFunc
ctx, cancel = context.WithDeadline(context.Background(), deadline)
defer cancel()
}
walkfs = cfs.WithContext(ctx)
}
walk := func(p string, f fs.File, err error) error {
if err != nil {
return err
}
info, err := f.Stat()
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil
}
return err
}
etag, err := infs.ETag(p, info)
if err != nil {
f.Close()
return err
}
full := prefix + p
pname, err := c.match(fullpat, full)
if err != nil {
return err
}
prepend := -1
id, ok := ids[string(pname)]
if !ok {
prepend = st.findPrepend(idx, string(pname))
if prepend >= 0 {
id = inlineToID(idx, prepend)
} else {
id = nextID
nextID++
}
}
ret, err := idx.Inputs.Append(full, etag, id)
if err != nil {
// FIXME: on ErrETagChanged, force a rebuild?
// For now, don't get wedged:
if errors.Is(err, blockfmt.ErrETagChanged) {
return nil
}
return err
}
if !ret {
// file is not new
seek = p
if time.Since(start) >= maxDuration {
return errStop
}
return nil
}
fm, err := st.conf.Format(format, p, st.def.Inputs[i].Hints)
if err != nil {
return err
}
if fm == nil {
// TODO: insist that definitions contain
// patterns that make the format of any
// matching file unambiguous
return fmt.Errorf("couldn't determine format of file %s", p)
}
ids[string(pname)] = id
total++
size += info.Size()
part, err := c.add(fullpat, blockfmt.Input{
Path: full,
Size: info.Size(),
ETag: etag,
R: f,
F: fm,
})
if err != nil {
return err
}
if prepend >= 0 {
part.prepend = prepend
}
seek = p
if total >= maxInputs || size >= maxSize || time.Since(start) >= maxDuration {
return errStop
}
return nil
}
pat, err = fsutil.ToGlob(pat)
if err != nil {
return 0, err
}
if strings.HasSuffix(seek, "/") {
st.conf.logf("fixing bad cursor %q", seek)
seek = strings.TrimSuffix(seek, "/")
}
err = fsutil.WalkGlob(walkfs, seek, pat, walk)
idx.Cursors[i] = seek
if err == errStop || errors.Is(err, context.DeadlineExceeded) {
if pe, ok := err.(*fs.PathError); ok {
// we aborted early and know the path we
// were last scanning, so use that as
// the cursor instead of seek
idx.Cursors[i] = pe.Path
}
complete = false
break
} else if err != nil {
return 0, err
}
}
idx.Scanning = !complete
if total == 0 {
// either we are complete
// or we updated the seek position
if flushOnComplete {
return 0, st.flush(context.Background(), idx)
}
return 0, nil
}
for i := range c.parts {
if c.parts[i].prepend >= 0 {
st.deleteInline(idx, c.parts[i].prepend)
}
}
err = st.force(context.Background(), idx, c.parts)
if err != nil {
st.invalidate()
return 0, err
}
if st.conf.Verbose {
st.conf.Logf("successfully scanned %v bytes (max %v)", size, maxSize)
}
return total, nil
}