-
Notifications
You must be signed in to change notification settings - Fork 35
/
writer.go
362 lines (313 loc) · 8.96 KB
/
writer.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// Copyright 2019 The go-hep Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rtree
import (
"fmt"
"reflect"
"regexp"
"strings"
"go-hep.org/x/hep/groot/internal/rcompress"
"go-hep.org/x/hep/groot/rbase"
"go-hep.org/x/hep/groot/riofs"
"go-hep.org/x/hep/groot/root"
"go-hep.org/x/hep/groot/rvers"
)
// Writer is the interface that wraps the Write method for Trees.
type Writer interface {
Tree
// Write writes the event data to ROOT storage and returns the number
// of bytes (before compression, if any) written.
Write() (int, error)
// Flush commits the current contents of the tree to stable storage.
Flush() error
// Close writes metadata and closes the tree.
Close() error
}
// WriteOption configures how a ROOT tree (and its branches) should be created.
type WriteOption func(opt *wopt) error
type wopt struct {
title string // title of the writer tree
bufsize int32 // buffer size for branches
splitlvl int32 // maximum split-level for branches
compress int32 // compression algorithm name and compression level
}
// WithLZ4 configures a ROOT tree to use LZ4 as a compression mechanism.
func WithLZ4(level int) WriteOption {
return func(opt *wopt) error {
opt.compress = rcompress.Settings{Alg: rcompress.LZ4, Lvl: level}.Compression()
return nil
}
}
// WithLZMA configures a ROOT tree to use LZMA as a compression mechanism.
func WithLZMA(level int) WriteOption {
return func(opt *wopt) error {
opt.compress = rcompress.Settings{Alg: rcompress.LZMA, Lvl: level}.Compression()
return nil
}
}
// WithoutCompression configures a ROOT tree to not use any compression mechanism.
func WithoutCompression() WriteOption {
return func(opt *wopt) error {
opt.compress = 0
return nil
}
}
// WithZlib configures a ROOT tree to use zlib as a compression mechanism.
func WithZlib(level int) WriteOption {
return func(opt *wopt) error {
opt.compress = rcompress.Settings{Alg: rcompress.ZLIB, Lvl: level}.Compression()
return nil
}
}
// WithBasketSize configures a ROOT tree to use 'size' (in bytes) as a basket buffer size.
// if size is <= 0, the default buffer size is used (DefaultBasketSize).
func WithBasketSize(size int) WriteOption {
return func(opt *wopt) error {
if size <= 0 {
size = defaultBasketSize
}
opt.bufsize = int32(size)
return nil
}
}
// WithTitle sets the title of the tree writer.
func WithTitle(title string) WriteOption {
return func(opt *wopt) error {
opt.title = title
return nil
}
}
type wtree struct {
ttree
wvars []WriteVar
}
// WriteVar describes a variable to be written out to a tree.
type WriteVar struct {
Name string // name of the variable
Value interface{} // pointer to the value to write
Count string // name of the branch holding the count-leaf value for slices
}
// WriteVarsFromStruct creates a slice of WriteVars from the ptr value.
// WriteVarsFromStruct panics if ptr is not a pointer to a struct value.
// WriteVarsFromStruct ignores fields that are not exported.
func WriteVarsFromStruct(ptr interface{}) []WriteVar {
rv := reflect.ValueOf(ptr)
if rv.Kind() != reflect.Ptr {
panic(fmt.Errorf("rtree: expect a pointer value, got %T", ptr))
}
rv = rv.Elem()
if rv.Kind() != reflect.Struct {
panic(fmt.Errorf("rtree: expect a pointer to struct value, got %T", ptr))
}
var (
reDims = regexp.MustCompile(`\w*?\[(\w*)\]+?`)
)
split := func(s string) (string, []string) {
n := s
if i := strings.Index(s, "["); i > 0 {
n = s[:i]
}
out := reDims.FindAllStringSubmatch(s, -1)
if len(out) == 0 {
return n, nil
}
dims := make([]string, len(out))
for i := range out {
dims[i] = out[i][1]
}
return n, dims
}
var (
rt = rv.Type()
wvars = make([]WriteVar, 0, rt.NumField())
)
for i := 0; i < rt.NumField(); i++ {
var (
ft = rt.Field(i)
fv = rv.Field(i)
)
if ft.Name != strings.Title(ft.Name) {
// not exported. ignore.
continue
}
wvar := WriteVar{
Name: ft.Tag.Get("groot"),
Value: fv.Addr().Interface(),
}
if wvar.Name == "" {
wvar.Name = ft.Name
}
if strings.Contains(wvar.Name, "[") {
switch ft.Type.Kind() {
case reflect.Slice:
sli, dims := split(wvar.Name)
if len(dims) > 1 {
panic(fmt.Errorf("rtree: invalid number of slice-dimensions for field %q: %q", ft.Name, wvar.Name))
}
wvar.Name = sli
wvar.Count = dims[0]
case reflect.Array:
arr, dims := split(wvar.Name)
if len(dims) > 3 {
panic(fmt.Errorf("rtree: invalid number of array-dimension for field %q: %q", ft.Name, wvar.Name))
}
wvar.Name = arr
default:
panic(fmt.Errorf("rtree: invalid field type for %q, or invalid struct-tag %q: %T", ft.Name, wvar.Name, fv.Interface()))
}
}
switch ft.Type.Kind() {
case reflect.Int, reflect.Uint, reflect.UnsafePointer, reflect.Uintptr, reflect.Chan, reflect.Interface:
panic(fmt.Errorf("rtree: invalid field type for %q: %T", ft.Name, fv.Interface()))
case reflect.Map:
panic(fmt.Errorf("rtree: invalid field type for %q: %T (not yet supported)", ft.Name, fv.Interface()))
}
wvars = append(wvars, wvar)
}
return wvars
}
// WriteVarsFromTree creates a slice of WriteVars from the tree value.
func WriteVarsFromTree(t Tree) []WriteVar {
rvars := NewScanVars(t)
wvars := make([]WriteVar, len(rvars))
for i, rvar := range rvars {
wvars[i] = WriteVar{
Name: rvar.Name,
Value: reflect.New(reflect.TypeOf(rvar.Value).Elem()).Interface(),
Count: rvar.count,
}
}
return wvars
}
// NewWriter creates a new Tree with the given name and under the given
// directory dir, ready to be filled with data.
func NewWriter(dir riofs.Directory, name string, vars []WriteVar, opts ...WriteOption) (Writer, error) {
if dir == nil {
return nil, fmt.Errorf("rtree: missing parent directory")
}
w := &wtree{
ttree: ttree{
f: fileOf(dir),
dir: dir,
rvers: rvers.Tree,
named: *rbase.NewNamed(name, ""),
attline: *rbase.NewAttLine(),
attfill: *rbase.NewAttFill(),
attmarker: *rbase.NewAttMarker(),
weight: 1,
scanField: 25,
defaultEntryOffsetLen: 1000,
maxEntries: 1000000000000,
maxEntryLoop: 1000000000000,
autoSave: -300000000,
autoFlush: -30000000,
estimate: 1000000,
},
wvars: vars,
}
cfg := wopt{
bufsize: defaultBasketSize,
splitlvl: defaultSplitLevel,
compress: w.ttree.f.Compression(),
}
for _, opt := range opts {
err := opt(&cfg)
if err != nil {
return nil, fmt.Errorf("rtree: could not configure tree writer: %w", err)
}
}
w.ttree.named.SetTitle(cfg.title)
for _, v := range vars {
b, err := newBranchFromWVars(w, v.Name, []WriteVar{v}, nil, cfg)
if err != nil {
return nil, fmt.Errorf("rtree: could not create branch for write-var %#v: %w", v, err)
}
w.ttree.branches = append(w.ttree.branches, b)
}
return w, nil
}
func (w *wtree) SetTitle(title string) { w.ttree.named.SetTitle(title) }
func (w *wtree) ROOTMerge(src root.Object) error {
switch src := src.(type) {
case Tree:
_, err := Copy(w, src)
if err != nil {
return fmt.Errorf("rtree: could not merge tree: %w", err)
}
return nil
default:
return fmt.Errorf("rtree: can not merge src=%T into dst=%T", src, w)
}
}
// Write writes the event data to ROOT storage and returns the number
// of bytes (before compression, if any) written.
func (w *wtree) Write() (int, error) {
var tot int
for _, b := range w.ttree.branches {
nbytes, err := b.write()
if err != nil {
return tot, fmt.Errorf("rtree: could not write branch %q: %w", b.Name(), err)
}
tot += nbytes
}
w.ttree.entries++
w.ttree.totBytes += int64(tot)
// FIXME(sbinet): autoflush
return tot, nil
}
// Flush commits the current contents of the tree to stable storage.
func (w *wtree) Flush() error {
for _, b := range w.ttree.branches {
err := b.flush()
if err != nil {
return fmt.Errorf("rtree: could not flush branch %q: %w", b.Name(), err)
}
}
return nil
}
// Close writes metadata and closes the tree.
func (w *wtree) Close() error {
if err := w.Flush(); err != nil {
return fmt.Errorf("rtree: could not flush tree %q: %w", w.Name(), err)
}
if err := w.ttree.dir.Put(w.Name(), w); err != nil {
return fmt.Errorf("rtree: could not save tree %q: %w", w.Name(), err)
}
return nil
}
func (w *wtree) loadEntry(i int64) error {
return fmt.Errorf("rtree: Tree writer can not be read from")
}
func fileOf(d riofs.Directory) *riofs.File {
const max = 1<<31 - 1
for i := 0; i < max; i++ {
p := d.Parent()
if p == nil {
return d.(*riofs.File)
}
d = p
}
panic("impossible")
}
func flattenArrayType(rt reflect.Type) (reflect.Type, []int) {
var (
shape []int
kind = rt.Kind()
)
const max = 1<<31 - 1
for i := 0; i < max; i++ {
if kind != reflect.Array {
return rt, shape
}
shape = append(shape, rt.Len())
rt = rt.Elem()
kind = rt.Kind()
}
panic("impossible")
}
var (
_ Tree = (*wtree)(nil)
_ Writer = (*wtree)(nil)
_ root.Merger = (*wtree)(nil)
)