|
| 1 | +// Copyright 2021 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package managedwriter |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "fmt" |
| 20 | + "runtime" |
| 21 | + "strings" |
| 22 | + |
| 23 | + storage "cloud.google.com/go/bigquery/storage/apiv1beta2" |
| 24 | + "google.golang.org/api/option" |
| 25 | + storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" |
| 26 | +) |
| 27 | + |
| 28 | +// Client is a managed BigQuery Storage write client scoped to a single project. |
| 29 | +type Client struct { |
| 30 | + rawClient *storage.BigQueryWriteClient |
| 31 | + projectID string |
| 32 | +} |
| 33 | + |
| 34 | +// NewClient instantiates a new client. |
| 35 | +func NewClient(ctx context.Context, projectID string, opts ...option.ClientOption) (c *Client, err error) { |
| 36 | + numConns := runtime.GOMAXPROCS(0) |
| 37 | + if numConns > 4 { |
| 38 | + numConns = 4 |
| 39 | + } |
| 40 | + o := []option.ClientOption{ |
| 41 | + option.WithGRPCConnectionPool(numConns), |
| 42 | + } |
| 43 | + o = append(o, opts...) |
| 44 | + |
| 45 | + rawClient, err := storage.NewBigQueryWriteClient(ctx, o...) |
| 46 | + if err != nil { |
| 47 | + return nil, err |
| 48 | + } |
| 49 | + |
| 50 | + return &Client{ |
| 51 | + rawClient: rawClient, |
| 52 | + projectID: projectID, |
| 53 | + }, nil |
| 54 | +} |
| 55 | + |
| 56 | +// NewManagedStream establishes a new managed stream for appending data into a table. |
| 57 | +func (c *Client) NewManagedStream(ctx context.Context, opts ...WriterOption) (*ManagedStream, error) { |
| 58 | + |
| 59 | + ms := &ManagedStream{ |
| 60 | + streamSettings: defaultStreamSettings(), |
| 61 | + c: c, |
| 62 | + } |
| 63 | + |
| 64 | + // apply writer options |
| 65 | + for _, opt := range opts { |
| 66 | + opt(ms) |
| 67 | + } |
| 68 | + |
| 69 | + if err := c.validateOptions(ctx, ms); err != nil { |
| 70 | + return nil, err |
| 71 | + } |
| 72 | + |
| 73 | + if ms.streamSettings.streamID == "" { |
| 74 | + // not instantiated with a stream, construct one. |
| 75 | + streamName := fmt.Sprintf("%s/_default", ms.destinationTable) |
| 76 | + if ms.streamSettings.streamType != DefaultStream { |
| 77 | + // For everything but a default stream, we create a new stream on behalf of the user. |
| 78 | + req := &storagepb.CreateWriteStreamRequest{ |
| 79 | + Parent: ms.destinationTable, |
| 80 | + WriteStream: &storagepb.WriteStream{ |
| 81 | + Type: streamTypeToEnum(ms.streamSettings.streamType), |
| 82 | + }} |
| 83 | + resp, err := ms.c.rawClient.CreateWriteStream(ctx, req) |
| 84 | + if err != nil { |
| 85 | + return nil, fmt.Errorf("couldn't create write stream: %v", err) |
| 86 | + } |
| 87 | + streamName = resp.GetName() |
| 88 | + } |
| 89 | + ms.streamSettings.streamID = streamName |
| 90 | + // TODO(followup CLs): instantiate an appendstream client, flow controller, etc. |
| 91 | + } |
| 92 | + |
| 93 | + return ms, nil |
| 94 | +} |
| 95 | + |
| 96 | +// validateOptions is used to validate that we received a sane/compatible set of WriterOptions |
| 97 | +// for constructing a new managed stream. |
| 98 | +func (c *Client) validateOptions(ctx context.Context, ms *ManagedStream) error { |
| 99 | + if ms == nil { |
| 100 | + return fmt.Errorf("no managed stream definition") |
| 101 | + } |
| 102 | + if ms.streamSettings.streamID != "" { |
| 103 | + // User supplied a stream, we need to verify it exists. |
| 104 | + info, err := c.getWriteStream(ctx, ms.streamSettings.streamID) |
| 105 | + if err != nil { |
| 106 | + return fmt.Errorf("a streamname was specified, but lookup of stream failed: %v", err) |
| 107 | + } |
| 108 | + // update type and destination based on stream metadata |
| 109 | + ms.streamSettings.streamType = StreamType(info.Type.String()) |
| 110 | + ms.destinationTable = tableParentFromStreamName(ms.streamSettings.streamID) |
| 111 | + } |
| 112 | + if ms.destinationTable == "" { |
| 113 | + return fmt.Errorf("no destination table specified") |
| 114 | + } |
| 115 | + // we could auto-select DEFAULT here, but let's force users to be specific for now. |
| 116 | + if ms.StreamType() == "" { |
| 117 | + return fmt.Errorf("stream type wasn't specified") |
| 118 | + } |
| 119 | + return nil |
| 120 | +} |
| 121 | + |
| 122 | +// BatchCommit is used to commit one or more PendingStream streams belonging to the same table |
| 123 | +// as a single transaction. Streams must be finalized before committing. |
| 124 | +// |
| 125 | +// TODO: this currently exposes the raw proto response, but a future CL will wrap this with a nicer type. |
| 126 | +func (c *Client) BatchCommit(ctx context.Context, parentTable string, streamNames []string) (*storagepb.BatchCommitWriteStreamsResponse, error) { |
| 127 | + |
| 128 | + // determine table from first streamName, as all must share the same table. |
| 129 | + if len(streamNames) <= 0 { |
| 130 | + return nil, fmt.Errorf("no streamnames provided") |
| 131 | + } |
| 132 | + |
| 133 | + req := &storagepb.BatchCommitWriteStreamsRequest{ |
| 134 | + Parent: tableParentFromStreamName(streamNames[0]), |
| 135 | + WriteStreams: streamNames, |
| 136 | + } |
| 137 | + return c.rawClient.BatchCommitWriteStreams(ctx, req) |
| 138 | +} |
| 139 | + |
| 140 | +// getWriteStream returns information about a given write stream. |
| 141 | +// |
| 142 | +// It's primarily used for setup validation, and not exposed directly to end users. |
| 143 | +func (c *Client) getWriteStream(ctx context.Context, streamName string) (*storagepb.WriteStream, error) { |
| 144 | + req := &storagepb.GetWriteStreamRequest{ |
| 145 | + Name: streamName, |
| 146 | + } |
| 147 | + return c.rawClient.GetWriteStream(ctx, req) |
| 148 | +} |
| 149 | + |
| 150 | +// tableParentFromStreamName return the corresponding parent table |
| 151 | +// identifier given a fully qualified streamname. |
| 152 | +func tableParentFromStreamName(streamName string) string { |
| 153 | + // Stream IDs have the following prefix: |
| 154 | + // projects/{project}/datasets/{dataset}/tables/{table}/blah |
| 155 | + parts := strings.SplitN(streamName, "/", 7) |
| 156 | + if len(parts) < 7 { |
| 157 | + // invalid; just pass back the input |
| 158 | + return streamName |
| 159 | + } |
| 160 | + return strings.Join(parts[:6], "/") |
| 161 | +} |
0 commit comments