go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/analysis/internal/buildbucket/buildbucket.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 buildbucket contains logic of interacting with Buildbucket. 16 package buildbucket 17 18 import ( 19 "context" 20 "net/http" 21 22 "google.golang.org/grpc" 23 24 bbpb "go.chromium.org/luci/buildbucket/proto" 25 "go.chromium.org/luci/grpc/prpc" 26 27 "go.chromium.org/luci/analysis/internal/scopedauth" 28 ) 29 30 // testBBClientKey is the context key controls the use of buildbucket client test doubles in tests. 31 var testBBClientKey = "used in tests only for setting the mock buildbucket client" 32 33 type GetBuildsClient interface { 34 GetBuild(ctx context.Context, in *bbpb.GetBuildRequest, opts ...grpc.CallOption) (*bbpb.Build, error) 35 } 36 37 // useBuildsClientForTesting specifies that the given test double shall be used 38 // instead of making calls to buildbucket. 39 func useBuildsClientForTesting(ctx context.Context, client GetBuildsClient) context.Context { 40 return context.WithValue(ctx, &testBBClientKey, client) 41 } 42 43 func newBuildsClient(ctx context.Context, host, project string) (GetBuildsClient, error) { 44 if mockClient, ok := ctx.Value(&testBBClientKey).(GetBuildsClient); ok { 45 return mockClient, nil 46 } 47 48 t, err := scopedauth.GetRPCTransport(ctx, project) 49 if err != nil { 50 return nil, err 51 } 52 return bbpb.NewBuildsPRPCClient( 53 &prpc.Client{ 54 C: &http.Client{Transport: t}, 55 Host: host, 56 Options: prpc.DefaultOptions(), 57 }), nil 58 } 59 60 // Client is the client to communicate with Buildbucket. 61 // It wraps a bbpb.BuildsClient. 62 type Client struct { 63 client GetBuildsClient 64 } 65 66 // NewClient creates a client to communicate with Buildbucket, acting as the given 67 // LUCI project. 68 func NewClient(ctx context.Context, host, project string) (*Client, error) { 69 client, err := newBuildsClient(ctx, host, project) 70 if err != nil { 71 return nil, err 72 } 73 74 return &Client{ 75 client: client, 76 }, nil 77 } 78 79 // GetBuild returns bbpb.Build for the requested build. 80 func (c *Client) GetBuild(ctx context.Context, req *bbpb.GetBuildRequest) (*bbpb.Build, error) { 81 return c.client.GetBuild(ctx, req) 82 }