...

Source file src/cloud.google.com/go/kms/inventory/apiv1/key_dashboard_client.go

Documentation: cloud.google.com/go/kms/inventory/apiv1

     1  // Copyright 2024 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  // Code generated by protoc-gen-go_gapic. DO NOT EDIT.
    16  
    17  package inventory
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"io"
    23  	"math"
    24  	"net/http"
    25  	"net/url"
    26  	"time"
    27  
    28  	kmspb "cloud.google.com/go/kms/apiv1/kmspb"
    29  	inventorypb "cloud.google.com/go/kms/inventory/apiv1/inventorypb"
    30  	gax "github.com/googleapis/gax-go/v2"
    31  	"google.golang.org/api/googleapi"
    32  	"google.golang.org/api/iterator"
    33  	"google.golang.org/api/option"
    34  	"google.golang.org/api/option/internaloption"
    35  	gtransport "google.golang.org/api/transport/grpc"
    36  	httptransport "google.golang.org/api/transport/http"
    37  	"google.golang.org/grpc"
    38  	"google.golang.org/protobuf/encoding/protojson"
    39  	"google.golang.org/protobuf/proto"
    40  )
    41  
    42  var newKeyDashboardClientHook clientHook
    43  
    44  // KeyDashboardCallOptions contains the retry settings for each method of KeyDashboardClient.
    45  type KeyDashboardCallOptions struct {
    46  	ListCryptoKeys []gax.CallOption
    47  }
    48  
    49  func defaultKeyDashboardGRPCClientOptions() []option.ClientOption {
    50  	return []option.ClientOption{
    51  		internaloption.WithDefaultEndpoint("kmsinventory.googleapis.com:443"),
    52  		internaloption.WithDefaultEndpointTemplate("kmsinventory.UNIVERSE_DOMAIN:443"),
    53  		internaloption.WithDefaultMTLSEndpoint("kmsinventory.mtls.googleapis.com:443"),
    54  		internaloption.WithDefaultUniverseDomain("googleapis.com"),
    55  		internaloption.WithDefaultAudience("https://kmsinventory.googleapis.com/"),
    56  		internaloption.WithDefaultScopes(DefaultAuthScopes()...),
    57  		internaloption.EnableJwtWithScope(),
    58  		option.WithGRPCDialOption(grpc.WithDefaultCallOptions(
    59  			grpc.MaxCallRecvMsgSize(math.MaxInt32))),
    60  	}
    61  }
    62  
    63  func defaultKeyDashboardCallOptions() *KeyDashboardCallOptions {
    64  	return &KeyDashboardCallOptions{
    65  		ListCryptoKeys: []gax.CallOption{
    66  			gax.WithTimeout(60000 * time.Millisecond),
    67  		},
    68  	}
    69  }
    70  
    71  func defaultKeyDashboardRESTCallOptions() *KeyDashboardCallOptions {
    72  	return &KeyDashboardCallOptions{
    73  		ListCryptoKeys: []gax.CallOption{
    74  			gax.WithTimeout(60000 * time.Millisecond),
    75  		},
    76  	}
    77  }
    78  
    79  // internalKeyDashboardClient is an interface that defines the methods available from KMS Inventory API.
    80  type internalKeyDashboardClient interface {
    81  	Close() error
    82  	setGoogleClientInfo(...string)
    83  	Connection() *grpc.ClientConn
    84  	ListCryptoKeys(context.Context, *inventorypb.ListCryptoKeysRequest, ...gax.CallOption) *CryptoKeyIterator
    85  }
    86  
    87  // KeyDashboardClient is a client for interacting with KMS Inventory API.
    88  // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
    89  //
    90  // Provides a cross-region view of all Cloud KMS keys in a given Cloud project.
    91  type KeyDashboardClient struct {
    92  	// The internal transport-dependent client.
    93  	internalClient internalKeyDashboardClient
    94  
    95  	// The call options for this service.
    96  	CallOptions *KeyDashboardCallOptions
    97  }
    98  
    99  // Wrapper methods routed to the internal client.
   100  
   101  // Close closes the connection to the API service. The user should invoke this when
   102  // the client is no longer required.
   103  func (c *KeyDashboardClient) Close() error {
   104  	return c.internalClient.Close()
   105  }
   106  
   107  // setGoogleClientInfo sets the name and version of the application in
   108  // the `x-goog-api-client` header passed on each request. Intended for
   109  // use by Google-written clients.
   110  func (c *KeyDashboardClient) setGoogleClientInfo(keyval ...string) {
   111  	c.internalClient.setGoogleClientInfo(keyval...)
   112  }
   113  
   114  // Connection returns a connection to the API service.
   115  //
   116  // Deprecated: Connections are now pooled so this method does not always
   117  // return the same resource.
   118  func (c *KeyDashboardClient) Connection() *grpc.ClientConn {
   119  	return c.internalClient.Connection()
   120  }
   121  
   122  // ListCryptoKeys returns cryptographic keys managed by Cloud KMS in a given Cloud project.
   123  // Note that this data is sourced from snapshots, meaning it may not
   124  // completely reflect the actual state of key metadata at call time.
   125  func (c *KeyDashboardClient) ListCryptoKeys(ctx context.Context, req *inventorypb.ListCryptoKeysRequest, opts ...gax.CallOption) *CryptoKeyIterator {
   126  	return c.internalClient.ListCryptoKeys(ctx, req, opts...)
   127  }
   128  
   129  // keyDashboardGRPCClient is a client for interacting with KMS Inventory API over gRPC transport.
   130  //
   131  // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
   132  type keyDashboardGRPCClient struct {
   133  	// Connection pool of gRPC connections to the service.
   134  	connPool gtransport.ConnPool
   135  
   136  	// Points back to the CallOptions field of the containing KeyDashboardClient
   137  	CallOptions **KeyDashboardCallOptions
   138  
   139  	// The gRPC API client.
   140  	keyDashboardClient inventorypb.KeyDashboardServiceClient
   141  
   142  	// The x-goog-* metadata to be sent with each request.
   143  	xGoogHeaders []string
   144  }
   145  
   146  // NewKeyDashboardClient creates a new key dashboard service client based on gRPC.
   147  // The returned client must be Closed when it is done being used to clean up its underlying connections.
   148  //
   149  // Provides a cross-region view of all Cloud KMS keys in a given Cloud project.
   150  func NewKeyDashboardClient(ctx context.Context, opts ...option.ClientOption) (*KeyDashboardClient, error) {
   151  	clientOpts := defaultKeyDashboardGRPCClientOptions()
   152  	if newKeyDashboardClientHook != nil {
   153  		hookOpts, err := newKeyDashboardClientHook(ctx, clientHookParams{})
   154  		if err != nil {
   155  			return nil, err
   156  		}
   157  		clientOpts = append(clientOpts, hookOpts...)
   158  	}
   159  
   160  	connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...)
   161  	if err != nil {
   162  		return nil, err
   163  	}
   164  	client := KeyDashboardClient{CallOptions: defaultKeyDashboardCallOptions()}
   165  
   166  	c := &keyDashboardGRPCClient{
   167  		connPool:           connPool,
   168  		keyDashboardClient: inventorypb.NewKeyDashboardServiceClient(connPool),
   169  		CallOptions:        &client.CallOptions,
   170  	}
   171  	c.setGoogleClientInfo()
   172  
   173  	client.internalClient = c
   174  
   175  	return &client, nil
   176  }
   177  
   178  // Connection returns a connection to the API service.
   179  //
   180  // Deprecated: Connections are now pooled so this method does not always
   181  // return the same resource.
   182  func (c *keyDashboardGRPCClient) Connection() *grpc.ClientConn {
   183  	return c.connPool.Conn()
   184  }
   185  
   186  // setGoogleClientInfo sets the name and version of the application in
   187  // the `x-goog-api-client` header passed on each request. Intended for
   188  // use by Google-written clients.
   189  func (c *keyDashboardGRPCClient) setGoogleClientInfo(keyval ...string) {
   190  	kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
   191  	kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "grpc", grpc.Version)
   192  	c.xGoogHeaders = []string{"x-goog-api-client", gax.XGoogHeader(kv...)}
   193  }
   194  
   195  // Close closes the connection to the API service. The user should invoke this when
   196  // the client is no longer required.
   197  func (c *keyDashboardGRPCClient) Close() error {
   198  	return c.connPool.Close()
   199  }
   200  
   201  // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
   202  type keyDashboardRESTClient struct {
   203  	// The http endpoint to connect to.
   204  	endpoint string
   205  
   206  	// The http client.
   207  	httpClient *http.Client
   208  
   209  	// The x-goog-* headers to be sent with each request.
   210  	xGoogHeaders []string
   211  
   212  	// Points back to the CallOptions field of the containing KeyDashboardClient
   213  	CallOptions **KeyDashboardCallOptions
   214  }
   215  
   216  // NewKeyDashboardRESTClient creates a new key dashboard service rest client.
   217  //
   218  // Provides a cross-region view of all Cloud KMS keys in a given Cloud project.
   219  func NewKeyDashboardRESTClient(ctx context.Context, opts ...option.ClientOption) (*KeyDashboardClient, error) {
   220  	clientOpts := append(defaultKeyDashboardRESTClientOptions(), opts...)
   221  	httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...)
   222  	if err != nil {
   223  		return nil, err
   224  	}
   225  
   226  	callOpts := defaultKeyDashboardRESTCallOptions()
   227  	c := &keyDashboardRESTClient{
   228  		endpoint:    endpoint,
   229  		httpClient:  httpClient,
   230  		CallOptions: &callOpts,
   231  	}
   232  	c.setGoogleClientInfo()
   233  
   234  	return &KeyDashboardClient{internalClient: c, CallOptions: callOpts}, nil
   235  }
   236  
   237  func defaultKeyDashboardRESTClientOptions() []option.ClientOption {
   238  	return []option.ClientOption{
   239  		internaloption.WithDefaultEndpoint("https://kmsinventory.googleapis.com"),
   240  		internaloption.WithDefaultEndpointTemplate("https://kmsinventory.UNIVERSE_DOMAIN"),
   241  		internaloption.WithDefaultMTLSEndpoint("https://kmsinventory.mtls.googleapis.com"),
   242  		internaloption.WithDefaultUniverseDomain("googleapis.com"),
   243  		internaloption.WithDefaultAudience("https://kmsinventory.googleapis.com/"),
   244  		internaloption.WithDefaultScopes(DefaultAuthScopes()...),
   245  	}
   246  }
   247  
   248  // setGoogleClientInfo sets the name and version of the application in
   249  // the `x-goog-api-client` header passed on each request. Intended for
   250  // use by Google-written clients.
   251  func (c *keyDashboardRESTClient) setGoogleClientInfo(keyval ...string) {
   252  	kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
   253  	kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN")
   254  	c.xGoogHeaders = []string{"x-goog-api-client", gax.XGoogHeader(kv...)}
   255  }
   256  
   257  // Close closes the connection to the API service. The user should invoke this when
   258  // the client is no longer required.
   259  func (c *keyDashboardRESTClient) Close() error {
   260  	// Replace httpClient with nil to force cleanup.
   261  	c.httpClient = nil
   262  	return nil
   263  }
   264  
   265  // Connection returns a connection to the API service.
   266  //
   267  // Deprecated: This method always returns nil.
   268  func (c *keyDashboardRESTClient) Connection() *grpc.ClientConn {
   269  	return nil
   270  }
   271  func (c *keyDashboardGRPCClient) ListCryptoKeys(ctx context.Context, req *inventorypb.ListCryptoKeysRequest, opts ...gax.CallOption) *CryptoKeyIterator {
   272  	hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))}
   273  
   274  	hds = append(c.xGoogHeaders, hds...)
   275  	ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
   276  	opts = append((*c.CallOptions).ListCryptoKeys[0:len((*c.CallOptions).ListCryptoKeys):len((*c.CallOptions).ListCryptoKeys)], opts...)
   277  	it := &CryptoKeyIterator{}
   278  	req = proto.Clone(req).(*inventorypb.ListCryptoKeysRequest)
   279  	it.InternalFetch = func(pageSize int, pageToken string) ([]*kmspb.CryptoKey, string, error) {
   280  		resp := &inventorypb.ListCryptoKeysResponse{}
   281  		if pageToken != "" {
   282  			req.PageToken = pageToken
   283  		}
   284  		if pageSize > math.MaxInt32 {
   285  			req.PageSize = math.MaxInt32
   286  		} else if pageSize != 0 {
   287  			req.PageSize = int32(pageSize)
   288  		}
   289  		err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
   290  			var err error
   291  			resp, err = c.keyDashboardClient.ListCryptoKeys(ctx, req, settings.GRPC...)
   292  			return err
   293  		}, opts...)
   294  		if err != nil {
   295  			return nil, "", err
   296  		}
   297  
   298  		it.Response = resp
   299  		return resp.GetCryptoKeys(), resp.GetNextPageToken(), nil
   300  	}
   301  	fetch := func(pageSize int, pageToken string) (string, error) {
   302  		items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
   303  		if err != nil {
   304  			return "", err
   305  		}
   306  		it.items = append(it.items, items...)
   307  		return nextPageToken, nil
   308  	}
   309  
   310  	it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
   311  	it.pageInfo.MaxSize = int(req.GetPageSize())
   312  	it.pageInfo.Token = req.GetPageToken()
   313  
   314  	return it
   315  }
   316  
   317  // ListCryptoKeys returns cryptographic keys managed by Cloud KMS in a given Cloud project.
   318  // Note that this data is sourced from snapshots, meaning it may not
   319  // completely reflect the actual state of key metadata at call time.
   320  func (c *keyDashboardRESTClient) ListCryptoKeys(ctx context.Context, req *inventorypb.ListCryptoKeysRequest, opts ...gax.CallOption) *CryptoKeyIterator {
   321  	it := &CryptoKeyIterator{}
   322  	req = proto.Clone(req).(*inventorypb.ListCryptoKeysRequest)
   323  	unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
   324  	it.InternalFetch = func(pageSize int, pageToken string) ([]*kmspb.CryptoKey, string, error) {
   325  		resp := &inventorypb.ListCryptoKeysResponse{}
   326  		if pageToken != "" {
   327  			req.PageToken = pageToken
   328  		}
   329  		if pageSize > math.MaxInt32 {
   330  			req.PageSize = math.MaxInt32
   331  		} else if pageSize != 0 {
   332  			req.PageSize = int32(pageSize)
   333  		}
   334  		baseUrl, err := url.Parse(c.endpoint)
   335  		if err != nil {
   336  			return nil, "", err
   337  		}
   338  		baseUrl.Path += fmt.Sprintf("/v1/%v/cryptoKeys", req.GetParent())
   339  
   340  		params := url.Values{}
   341  		params.Add("$alt", "json;enum-encoding=int")
   342  		if req.GetPageSize() != 0 {
   343  			params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize()))
   344  		}
   345  		if req.GetPageToken() != "" {
   346  			params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken()))
   347  		}
   348  
   349  		baseUrl.RawQuery = params.Encode()
   350  
   351  		// Build HTTP headers from client and context metadata.
   352  		hds := append(c.xGoogHeaders, "Content-Type", "application/json")
   353  		headers := gax.BuildHeaders(ctx, hds...)
   354  		e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
   355  			if settings.Path != "" {
   356  				baseUrl.Path = settings.Path
   357  			}
   358  			httpReq, err := http.NewRequest("GET", baseUrl.String(), nil)
   359  			if err != nil {
   360  				return err
   361  			}
   362  			httpReq.Header = headers
   363  
   364  			httpRsp, err := c.httpClient.Do(httpReq)
   365  			if err != nil {
   366  				return err
   367  			}
   368  			defer httpRsp.Body.Close()
   369  
   370  			if err = googleapi.CheckResponse(httpRsp); err != nil {
   371  				return err
   372  			}
   373  
   374  			buf, err := io.ReadAll(httpRsp.Body)
   375  			if err != nil {
   376  				return err
   377  			}
   378  
   379  			if err := unm.Unmarshal(buf, resp); err != nil {
   380  				return err
   381  			}
   382  
   383  			return nil
   384  		}, opts...)
   385  		if e != nil {
   386  			return nil, "", e
   387  		}
   388  		it.Response = resp
   389  		return resp.GetCryptoKeys(), resp.GetNextPageToken(), nil
   390  	}
   391  
   392  	fetch := func(pageSize int, pageToken string) (string, error) {
   393  		items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
   394  		if err != nil {
   395  			return "", err
   396  		}
   397  		it.items = append(it.items, items...)
   398  		return nextPageToken, nil
   399  	}
   400  
   401  	it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
   402  	it.pageInfo.MaxSize = int(req.GetPageSize())
   403  	it.pageInfo.Token = req.GetPageToken()
   404  
   405  	return it
   406  }
   407  

View as plain text