-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
storage_iterator.go
377 lines (348 loc) · 9.38 KB
/
storage_iterator.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
// Copyright 2023 Google LLC
//
// 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 bigquery
import (
"context"
"errors"
"fmt"
"io"
"sync"
"sync/atomic"
"time"
"cloud.google.com/go/bigquery/internal/query"
"cloud.google.com/go/bigquery/storage/apiv1/storagepb"
"github.com/googleapis/gax-go/v2"
"golang.org/x/sync/semaphore"
"google.golang.org/api/iterator"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// storageArrowIterator is a raw interface for getting data from Storage Read API
type storageArrowIterator struct {
done uint32 // atomic flag
initialized bool
errs chan error
schema Schema
rawSchema []byte
records chan *ArrowRecordBatch
rs *readSession
}
var _ ArrowIterator = &storageArrowIterator{}
func newStorageRowIteratorFromTable(ctx context.Context, table *Table, rsProjectID string, ordered bool) (*RowIterator, error) {
md, err := table.Metadata(ctx)
if err != nil {
return nil, err
}
rs, err := table.c.rc.sessionForTable(ctx, table, rsProjectID, ordered)
if err != nil {
return nil, err
}
it, err := newStorageRowIterator(rs, md.Schema)
if err != nil {
return nil, err
}
if rs.bqSession == nil {
return nil, errors.New("read session not initialized")
}
arrowSerializedSchema := rs.bqSession.GetArrowSchema().GetSerializedSchema()
dec, err := newArrowDecoder(arrowSerializedSchema, md.Schema)
if err != nil {
return nil, err
}
it.arrowDecoder = dec
it.Schema = md.Schema
return it, nil
}
func newStorageRowIteratorFromJob(ctx context.Context, j *Job) (*RowIterator, error) {
// Needed to fetch destination table
job, err := j.c.JobFromProject(ctx, j.projectID, j.jobID, j.location)
if err != nil {
return nil, err
}
cfg, err := job.Config()
if err != nil {
return nil, err
}
qcfg := cfg.(*QueryConfig)
if qcfg.Dst == nil {
if !job.isScript() {
return nil, fmt.Errorf("job has no destination table to read")
}
lastJob, err := resolveLastChildSelectJob(ctx, job)
if err != nil {
return nil, err
}
return newStorageRowIteratorFromJob(ctx, lastJob)
}
ordered := query.HasOrderedResults(qcfg.Q)
return newStorageRowIteratorFromTable(ctx, qcfg.Dst, job.projectID, ordered)
}
func resolveLastChildSelectJob(ctx context.Context, job *Job) (*Job, error) {
childJobs := []*Job{}
it := job.Children(ctx)
for {
job, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, fmt.Errorf("failed to resolve table for script job: %w", err)
}
if !job.isSelectQuery() {
continue
}
childJobs = append(childJobs, job)
}
if len(childJobs) == 0 {
return nil, fmt.Errorf("failed to resolve table for script job: no child jobs found")
}
return childJobs[0], nil
}
func newRawStorageRowIterator(rs *readSession, schema Schema) (*storageArrowIterator, error) {
arrowIt := &storageArrowIterator{
rs: rs,
schema: schema,
records: make(chan *ArrowRecordBatch, rs.settings.maxWorkerCount+1),
errs: make(chan error, rs.settings.maxWorkerCount+1),
}
if rs.bqSession == nil {
err := rs.start()
if err != nil {
return nil, err
}
}
arrowIt.rawSchema = rs.bqSession.GetArrowSchema().GetSerializedSchema()
return arrowIt, nil
}
func newStorageRowIterator(rs *readSession, schema Schema) (*RowIterator, error) {
arrowIt, err := newRawStorageRowIterator(rs, schema)
if err != nil {
return nil, err
}
totalRows := arrowIt.rs.bqSession.EstimatedRowCount
it := &RowIterator{
ctx: rs.ctx,
arrowIterator: arrowIt,
TotalRows: uint64(totalRows),
rows: [][]Value{},
}
it.nextFunc = nextFuncForStorageIterator(it)
it.pageInfo = &iterator.PageInfo{
Token: "",
MaxSize: int(totalRows),
}
return it, nil
}
func nextFuncForStorageIterator(it *RowIterator) func() error {
return func() error {
if len(it.rows) > 0 {
return nil
}
record, err := it.arrowIterator.Next()
if err == iterator.Done {
if len(it.rows) == 0 {
return iterator.Done
}
return nil
}
if err != nil {
return err
}
if it.Schema == nil {
it.Schema = it.arrowIterator.Schema()
}
rows, err := it.arrowDecoder.decodeArrowRecords(record)
if err != nil {
return err
}
it.rows = rows
return nil
}
}
func (it *storageArrowIterator) init() error {
if it.initialized {
return nil
}
bqSession := it.rs.bqSession
if bqSession == nil {
return errors.New("read session not initialized")
}
streams := bqSession.Streams
if len(streams) == 0 {
return iterator.Done
}
wg := sync.WaitGroup{}
wg.Add(len(streams))
sem := semaphore.NewWeighted(int64(it.rs.settings.maxWorkerCount))
go func() {
wg.Wait()
close(it.records)
close(it.errs)
it.markDone()
}()
go func() {
for _, readStream := range streams {
err := sem.Acquire(it.rs.ctx, 1)
if err != nil {
wg.Done()
continue
}
go func(readStreamName string) {
it.processStream(readStreamName)
sem.Release(1)
wg.Done()
}(readStream.Name)
}
}()
it.initialized = true
return nil
}
func (it *storageArrowIterator) markDone() {
atomic.StoreUint32(&it.done, 1)
}
func (it *storageArrowIterator) isDone() bool {
return atomic.LoadUint32(&it.done) != 0
}
func (it *storageArrowIterator) processStream(readStream string) {
bo := gax.Backoff{}
var offset int64
for {
rowStream, err := it.rs.readRows(&storagepb.ReadRowsRequest{
ReadStream: readStream,
Offset: offset,
})
if err != nil {
serr := it.handleProcessStreamError(readStream, bo, err)
if serr != nil {
return
}
continue
}
offset, err = it.consumeRowStream(readStream, rowStream, offset)
if errors.Is(err, io.EOF) {
return
}
if err != nil {
serr := it.handleProcessStreamError(readStream, bo, err)
if serr != nil {
return
}
// try to re-open row stream with updated offset
}
}
}
// handleProcessStreamError check if err is retryable,
// waiting with exponential backoff in that scenario.
// If error is not retryable, queue up err to be sent to user.
// Return error if should exit the goroutine.
func (it *storageArrowIterator) handleProcessStreamError(readStream string, bo gax.Backoff, err error) error {
if it.rs.ctx.Err() != nil { // context cancelled, don't try again
return it.rs.ctx.Err()
}
backoff, shouldRetry := retryReadRows(bo, err)
if shouldRetry {
if err := gax.Sleep(it.rs.ctx, backoff); err != nil {
return err // context cancelled
}
return nil
}
select {
case it.errs <- fmt.Errorf("failed to read rows on stream %s: %w", readStream, err):
return nil
case <-it.rs.ctx.Done():
return context.Canceled
}
}
func retryReadRows(bo gax.Backoff, err error) (time.Duration, bool) {
s, ok := status.FromError(err)
if !ok {
return bo.Pause(), false
}
switch s.Code() {
case codes.Aborted,
codes.Canceled,
codes.DeadlineExceeded,
codes.Internal,
codes.Unavailable:
return bo.Pause(), true
}
return bo.Pause(), false
}
func (it *storageArrowIterator) consumeRowStream(readStream string, rowStream storagepb.BigQueryRead_ReadRowsClient, offset int64) (int64, error) {
for {
r, err := rowStream.Recv()
if err != nil {
if err == io.EOF {
return offset, err
}
return offset, fmt.Errorf("failed to consume rows on stream %s: %w", readStream, err)
}
if r.RowCount > 0 {
offset += r.RowCount
recordBatch := r.GetArrowRecordBatch()
it.records <- &ArrowRecordBatch{
PartitionID: readStream,
Schema: it.rawSchema,
Data: recordBatch.SerializedRecordBatch,
}
}
}
}
// next return the next batch of rows as an arrow.Record.
// Accessing Arrow Records directly has the drawnback of having to deal
// with memory management.
func (it *storageArrowIterator) Next() (*ArrowRecordBatch, error) {
if err := it.init(); err != nil {
return nil, err
}
if len(it.records) > 0 {
return <-it.records, nil
}
if it.isDone() {
return nil, iterator.Done
}
select {
case record := <-it.records:
if record == nil {
return nil, iterator.Done
}
return record, nil
case err := <-it.errs:
return nil, err
case <-it.rs.ctx.Done():
return nil, it.rs.ctx.Err()
}
}
func (it *storageArrowIterator) SerializedArrowSchema() []byte {
return it.rawSchema
}
func (it *storageArrowIterator) Schema() Schema {
return it.schema
}
// IsAccelerated check if the current RowIterator is
// being accelerated by Storage API.
func (it *RowIterator) IsAccelerated() bool {
return it.arrowIterator != nil
}
// ArrowIterator gives access to the raw Arrow Record Batch stream to be consumed directly.
// Experimental: this interface is experimental and may be modified or removed in future versions,
// regardless of any other documented package stability guarantees.
// Don't try to mix RowIterator.Next and ArrowIterator.Next calls.
func (it *RowIterator) ArrowIterator() (ArrowIterator, error) {
if !it.IsAccelerated() {
// TODO: can we convert plain RowIterator based on JSON API to an Arrow Stream ?
return nil, errors.New("bigquery: require storage read API to be enabled")
}
return it.arrowIterator, nil
}