go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/buildbucket/appengine/internal/clients/bq.go (about)

     1  // Copyright 2022 The LUCI Authors.
     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  //      http://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 clients
    16  
    17  import (
    18  	"context"
    19  	"net/http"
    20  
    21  	"cloud.google.com/go/bigquery"
    22  	"google.golang.org/api/option"
    23  
    24  	lucibq "go.chromium.org/luci/common/bq"
    25  	"go.chromium.org/luci/server/auth"
    26  )
    27  
    28  var bqClientCtxKey = "holds the global bigquery client"
    29  
    30  type BqClient interface {
    31  	// Insert a row into a BigQuery table
    32  	Insert(ctx context.Context, dataset string, table string, row *lucibq.Row) error
    33  }
    34  type bqClientImpl struct {
    35  	client *bigquery.Client
    36  }
    37  
    38  // Ensure bqClientImpl implements BqClient.
    39  var _ BqClient = &bqClientImpl{}
    40  
    41  func (b *bqClientImpl) Insert(ctx context.Context, dataset string, table string, row *lucibq.Row) error {
    42  	t := b.client.Dataset(dataset).Table(table)
    43  	return t.Inserter().Put(ctx, row)
    44  }
    45  
    46  // NewBqClient creates a new BqClient.
    47  func NewBqClient(ctx context.Context, cloudProject string) (BqClient, error) {
    48  	t, err := auth.GetRPCTransport(ctx, auth.AsSelf, auth.WithScopes(auth.CloudOAuthScopes...))
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  	b, err := bigquery.NewClient(ctx, cloudProject, option.WithHTTPClient(&http.Client{Transport: t}))
    53  	if err != nil {
    54  		return nil, err
    55  	}
    56  	return &bqClientImpl{client: b}, nil
    57  }
    58  
    59  // WithBqClient returns a new context with the given bq client.
    60  func WithBqClient(ctx context.Context, client BqClient) context.Context {
    61  	return context.WithValue(ctx, &bqClientCtxKey, client)
    62  }
    63  
    64  // GetBqClient returns the bigquery Client installed in the current context.
    65  // Panics if there isn't one.
    66  func GetBqClient(ctx context.Context) BqClient {
    67  	return ctx.Value(&bqClientCtxKey).(BqClient)
    68  }